开发者

All possible permutations of a given String?

How would I do this in Ruby?

p "abc".all_possible_permutations

Would return:

[
  "abc",
  "acb",
  "bca",
  "bac",
  "cba",
  "cab",
]

Edit

开发者_如何学运维

Thanks to Jakub Hampl:

class String
  def all_possible_permutations
    self.chars.to_a.permutation.map(&:join)
  end
end


%w[a b c].permutation.map &:join


If someone doesnt want to use inbuilt function :

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)


One line:

p "abc".chars.permutation.map &:join

Sample output:

["abc", "acb", "bac", "bca", "cab", "cba"] 
  • p is optional
  • string could be a variable instead
  • chars is pretty quick, it separates the string into an array of single characters
  • map has tons of cool applications,it takes a object, and returns it after the block is done, in this case the operation join
  • &:join could be replaced with { |i| i.join } like this:

    p "abc".chars.permutation.map{ |i| i.join }


If anyone wants to have the code for this using basic algorithms, here is how you do it-

    $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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜