我将如何在Ruby中执行此操作?
p "abc".all_possible_permutations
Run Code Online (Sandbox Code Playgroud)
会回来:
[
"abc",
"acb",
"bca",
"bac",
"cba",
"cab",
]
Run Code Online (Sandbox Code Playgroud)
感谢Jakub Hampl:
class String
def all_possible_permutations
self.chars.to_a.permutation.map(&:join)
end
end
Run Code Online (Sandbox Code Playgroud)
Jak*_*mpl 30
%w[a b c].permutation.map &:join
Run Code Online (Sandbox Code Playgroud)
mde*_*dev 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)
Run Code Online (Sandbox Code Playgroud)
p "abc".chars.permutation.map &:join
Run Code Online (Sandbox Code Playgroud)
["abc", "acb", "bac", "bca", "cab", "cba"]
Run Code Online (Sandbox Code Playgroud)
&:join 可以替换为 { |i| i.join } 像这样:
p "abc".chars.permutation.map{ |i| 我加入 }