【问题标题】:Generate all possible combinations of strings including repeats for given length?生成所有可能的字符串组合,包括给定长度的重复?
【发布时间】:2013-03-04 00:03:08
【问题描述】:

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

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

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

【问题讨论】:

    标签: ruby string combinations


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      怎么样:

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

      缩短版如下:

      'aa'..'bb').to_a [ [0]“啊”, [1] "ab", [2]“交流”, [3]“广告”, [4] “AE”, [5]“AF”, [6] “ag”, [7]“啊”, [8]“爱”, [ 9] “阿杰”, [10] “阿克”, [11] “人”, [12] “我”, [13] “一个”, [14] “奥”, [15] “AP”, [16] “水”, [17] “阿尔”, [18] “作为”, [19] “在”, [20] “非”, [21] “av”, [22] “啊”, [23] “斧头”, [24] “啊”, [25] “阿兹”, [26] “巴”, [27] “bb” ]

      编辑:

      ...我已经根据长度生成了。

      然后使用长度。

      长度 = 2 (('a' * 长度) .. ('z' * 长度)).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 的时间长。随意在您自己的机器上运行基准测试。

      【讨论】:

      • 关闭,但我已根据长度生成。
      猜你喜欢
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2017-11-23
      相关资源
      最近更新 更多