生成所有可能的字符串组合,包括给定长度的重复?

时间:2013-03-04 00:03:09

标签: ruby string combinations

我需要根据长度生成字母az的所有可能组合。我知道我可以这样做:

('a'..'z').to_a.repeated_combination(2).map(&:join)

但问题是删除了重复项。如果长度为2,我需要aazz之间的所有内容,包括abba等。我知道这是一个简单的过程,但我不能得到它,我的谷歌已关闭。

2 个答案:

答案 0 :(得分:2)

怎么样:

('aa'..'zz').to_a

缩短版本如下:

'aa'..'bb').to_a
[
    [ 0] "aa",
    [ 1] "ab",
    [ 2] "ac",
    [ 3] "ad",
    [ 4] "ae",
    [ 5] "af",
    [ 6] "ag",
    [ 7] "ah",
    [ 8] "ai",
    [ 9] "aj",
    [10] "ak",
    [11] "al",
    [12] "am",
    [13] "an",
    [14] "ao",
    [15] "ap",
    [16] "aq",
    [17] "ar",
    [18] "as",
    [19] "at",
    [20] "au",
    [21] "av",
    [22] "aw",
    [23] "ax",
    [24] "ay",
    [25] "az",
    [26] "ba",
    [27] "bb"
]

编辑:

  

...我根据长度生成。

然后使用长度。

length = 2
(('a' * length) .. ('z' * length)).to_a

这是生成组合的一种非常快速的方法:

require 'benchmark'

N = 1_000

1.upto(3) do |length|
  puts %Q[Length: #{ length }, generating "#{ 'a' * length }" to "#{ 'z' * length }"]
  Benchmark.bm(11) do |b|
    b.report('permutation') { N.times { ('a'..'z').to_a.repeated_permutation(length).map(&:join) }}
    b.report('range') { N.times { (('a' * length) .. ('z' * length)).to_a }}
  end
end

哪个输出:

Length: 1, generating "a" to "z"
                  user     system      total        real
permutation   0.030000   0.000000   0.030000 (  0.028286)
range         0.010000   0.000000   0.010000 (  0.009942)
Length: 2, generating "aa" to "zz"
                  user     system      total        real
permutation   0.500000   0.010000   0.510000 (  0.504663)
range         0.240000   0.000000   0.240000 (  0.240362)
Length: 3, generating "aaa" to "zzz"
                  user     system      total        real
permutation  15.350000   0.140000  15.490000 ( 15.535756)
range         6.200000   0.000000   6.200000 (  6.221575)

“排列”的时间比我愿意等待4的时间长。随意在您自己的机器上运行基准测试。

答案 1 :(得分:1)

在这种情况下,您需要使用repeated_permutationArray Permutation