Ruby 排列(内置) - 结果不包含相邻的相同字母
感谢您昨天的帮助,也感谢您教我一些新东西。 :)
我还有另一个基于排列的问题...我的算法有效,但是我遇到的问题是生成的列表中缺少相同的相邻字符。
例如,如果我有字符列表 az,0-9,- 假设最大长度为 2,那么我应该看到 aa、bb、cc、dd、ee、ff 等,令人恶心。
length = 1
alphabet = [('a'..'z').to_a, ('0'..'9').to_a, ('-').to_a].flatten
prefix = 'file-'
suffix = '.txt'
while length < 3
alphabet.permutation(length).each do |x|
@name = prefix+x.join('').to_s+suffix
puts @name
end
length += 1
end
但是,我只看到以下内容:
file-ba.txt
file-bc.txt
请注意缺少的“bb”,并且这种情况会一直持续到程序完成。
我确信我错过了一些东西,只是不确定什么?
Thank you for your help yesterday and for teaching me something new as well. :)
I have another question based on permutation... the algorithm I have works however I have the issue that identical adjacent characters are missing from the list generated.
For example, if I have the character list a-z,0-9,- and let's say that the maximum length is 2, then I should see aa, bb, cc, dd, ee, ff, etc. ad nauseum.
length = 1
alphabet = [('a'..'z').to_a, ('0'..'9').to_a, ('-').to_a].flatten
prefix = 'file-'
suffix = '.txt'
while length < 3
alphabet.permutation(length).each do |x|
@name = prefix+x.join('').to_s+suffix
puts @name
end
length += 1
end
However, I am only seeing the following:
file-ba.txt
file-bc.txt
note the missing "bb" and this continues on until the program is finished.
I am sure I am missing something, just not sure what?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你想使用repeated_permutation而不是排列。
http://www.ruby-doc.org/core/classes/Array .html#M000289
它将生成包括“file-bb.txt”在内的所有排列。
I think you want to use repeated_permutation instead of permutation.
http://www.ruby-doc.org/core/classes/Array.html#M000289
It will generate all permutations including "file-bb.txt".
这就是什么是排列。 [1,2,3] 仅有的 6 种排列是
That's what a permutation is. The only 6 permutations of [1,2,3] are