1

在尝试迭代字母数组并生成所有 6 个字符(仅限 alpha)字符串时,我的迭代似乎在最内部嵌套循环的单个 while 循环之后结束。代码如下。想法?


alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

x1 = 0
x2 = 0
x3 = 0
x4 = 0
x5 = 0
x6 = 0

while x1<26
    y1 = alpha[x1]
    while x2<26
        y2 = alpha[x2]
        while x3<26
            y3 = alpha[x3]
            while x4<26
                y4 = alpha[x4]
                while x5<26
                    y5 = alpha[x5]
                    while x6<26
                        y6 = alpha[x6]
                        puts y1 + y2 + y3 + y4 + y5 + y6
                        x6 = x6 + 1
                    end
                    x5 = x5 + 1
                end
                x4 = x4 + 1
            end
            x3 = x3 + 1
        end
        x2 = x2 + 1
    end
    x1 = x1 + 1
end

编辑:我也很可能忽略了一种更简单的方法来实现预期的结果。如果是这样,请随时纠正我。

4

3 回答 3

4

为了更多地说明 Ruby,

loop.inject 'aaaaaa' do |memo|
  puts memo
  break if memo == 'zzzzzz'
  memo.next
end

或者简单地说:

( 'aaaaaa'..'zzzzzz' ).each &method( :puts )
于 2013-05-16T16:55:15.210 回答
2

这是做你想做的吗?它将生成所有唯一的排列,但不会加倍字符(如“aaaabb”)

('a'..'z').to_a.permutation(6).to_a

这是一个较短的版本,用于演示目的:

res = ('a'..'c').to_a.permutation(2).to_a 
res # => [["a", "b"], ["a", "c"], ["b", "a"], ["b", "c"], ["c", "a"], ["c", "b"]]
于 2013-05-16T16:38:31.170 回答
2
[*?a..?z].repeated_permutation(6).to_a.map &:join

在我的机器上给出致命的,无法分配内存,

[*?a..?z].repeated_permutation(2).to_a.map &:join

工作正常。

好的,调用#to_aafter是一个错误,它是#repeated_permutation这样工作的:

[*?a..?z].repeated_permutation( 6 ).each { |permutation| puts permutation.join }
于 2013-05-16T16:39:37.673 回答