我如何在Ruby中执行此操作?
p "abc".all_possible_permutations
会回来:
[
"abc",
"acb",
"bca",
"bac",
"cba",
"cab",
]
感谢Jakub Hampl:
class String
def all_possible_permutations
self.chars.to_a.permutation.map(&:join)
end
end
答案 0 :(得分:30)
%w[a b c].permutation.map &:join
答案 1 :(得分:10)
如果有人不想使用内置功能:
def permute(result,input)
if(input.length == 0)
return
end
if(input.length == 1)
puts result + input[0]
return
end
if(input.length == 2)
puts result + input[0] + input[1]
puts result + input[1] + input[0]
return
end
(0...input.length).step(1).each do |i|
firstpart = result+input[i]
secondpart = (i > 0 ? input[0..(i-1)] : '') + (input[(i+1)..-1] || '')
permute(firstpart,secondpart)
end
end
permute('',gets.chomp)
答案 2 :(得分:3)
p "abc".chars.permutation.map &:join
["abc", "acb", "bac", "bca", "cab", "cba"]
&amp ;: join可以替换为{| i | i.join}像这样:
p" abc" .chars.permutation.map {| i | i.join}
答案 3 :(得分:1)
如果有人想使用基本算法获得此代码,请按照以下方式进行操作 -
$count = 0
def permute(permuted_string, original_string, done_array)
if permuted_string.length == original_string.length
$count = $count+1
puts "#{$count} #{permuted_string}"
else
(0..original_string.length-1).each do |i|
if !done_array[i]
done_array[i] = true
permute(permuted_string+original_string[i], original_string, done_array)
done_array[i] = false
end
end
end
end
puts "Please enter the string for permutations"
input = gets.chomp
done_array = Array.new(input.length, false)
permute("", input, done_array)