【问题标题】:Permutation of files文件排列
【发布时间】:2016-04-18 15:41:15
【问题描述】:

我在一个目录中有 50 个文件,我想执行排列并以 25 个为一组获得所有可能的组合。如果你想看一个小例子,使用 od 3 组,它会是这样的:

file1 file2 file3
file1 file2 file4
file1 file2 file5
...
file50 file48 file49

为此,我使用的是 R 方法:

library(gtools)
args <- commandArgs(TRUE)

files <- list.files(args[1])
permutations(length(files), round(length(files)/2), files, repeats=FALSE)

这种方法非常缓慢。您知道使用awkbashpythonperl 的一些更快的替代方案吗?

【问题讨论】:

  • 这个问题确实需要一些示例输入/输出来给出有意义的答案。
  • 我认为这是因为答案是50! / (25! * 25!),这是一个非常非常大的数字
  • 在 R do.call(paste,expand.grid(rep(list(1:5),3))) 中尝试过这样的尝试,但这尝试创建一个 58GB 的​​向量,重复 1:50 和 25 次,这离我的计算机内存很远,所以我认为这是一个坏主意: )
  • 您实际上想要完成什么? 50 个元素中的 25 个的每一个排列总是很大的。 50 阶乘是 3 x 10 ^ 64,这是相当多的零。即使您“仅”取其中的 25 个,也仍然超过 15,511,210,043,330,985,984,000,000,即 25!
  • 如果我计算得当,它有 1.264106e+14 种可能性,即:126 410 606 437 752

标签: python r bash perl awk


【解决方案1】:

使用 Python,您可以使用 combinations 函数,如下所示:

from itertools import combinations
import os

for combo in combinations(os.listdir('.'), 25):
    print combo

【讨论】:

    【解决方案2】:

    来自perl faq

    use Algorithm::Permute;
    my @array = 'a'..'d';
    my $p_iterator = Algorithm::Permute->new ( \@array );
    while (my @perm = $p_iterator->next) {
       print "next permutation: (@perm)\n";
    }
    

    这会生成列表的每个排列,尽管有 50 个元素,但数量会不少。

    我不确定是否有一种方便的方法来选择和过滤子列表。我最初的想法是维护一个“看到”的列表。我会开始考虑在哈希中维护“已见”列表并跳过重复项,但您必须生成完整的排列列表才能做到这一点。

    另外还有combine

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use Math::Combinatorics;
    
    my @array      = 1 .. 9;
    my $count = 0;
    foreach my $comb ( combine (3, @array )) {
       print @$comb,"\n";
       print $count++,"\n";
    }
    

    3 路组合是:19,000 奇数。 4是:230300 5是:

    不知道 25 是什么 - 我还没准备好运行它!

    但请注意 - 这是一项大手术,因此无论您做什么都需要一段时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-14
      • 2012-02-12
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      相关资源
      最近更新 更多