在尝试迭代字母数组并生成所有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
编辑:我很可能忽略了一种更简单的方法来达到预期的效果。如果是这样,请随时纠正我。
答案 0 :(得分:4)
Tu更多地展示了Ruby方式,
loop.inject 'aaaaaa' do |memo|
puts memo
break if memo == 'zzzzzz'
memo.next
end
或者简单地说:
( 'aaaaaa'..'zzzzzz' ).each &method( :puts )
答案 1 :(得分: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"]]
答案 2 :(得分:2)
[*?a..?z].repeated_permutation(6).to_a.map &:join
致命致命,无法在我的机器上分配内存,
[*?a..?z].repeated_permutation(2).to_a.map &:join
工作正常。
好的,在#to_a
之后致电#repeated_permutation
是错误的,这就是它的工作原理:
[*?a..?z].repeated_permutation( 6 ).each { |permutation| puts permutation.join }