给定字符串的所有可能排列?

Rya*_*wis 25 ruby

我将如何在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)

  • 此外,如果您开始使用字符串:`"abc".chars.to_a.permutation.map&:join`. (6认同)

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)


jas*_*ard 6

一条线:

p "abc".chars.permutation.map &:join
Run Code Online (Sandbox Code Playgroud)

示例输出:

["abc", "acb", "bac", "bca", "cab", "cba"] 
Run Code Online (Sandbox Code Playgroud)
  • p 是可选的
  • 字符串可以是一个变量
  • chars 非常快,它将字符串分成单个字符的数组
  • map 有大量很酷的应用程序,它接受一个对象,并在块完成后返回它,在本例中是操作 join
  • &:join 可以替换为 { |i| i.join } 像这样:

    p "abc".chars.permutation.map{ |i| 我加入 }