Tuesday, June 18, 2013

Examples of permutations in Ruby

Permutations in arrays:
["1","2","3"].permutation.map { |a| a.join }
 => ["123", "132", "213", "231", "312", "321"] 

Permutations in stripped string:
"1 2 3".split(" ").permutation.map { |a| a.join }
 => ["123", "132", "213", "231", "312", "321"]


Permutations in hashtables:


x = {"2"=>"twenty","3"=>"thirty","4"=>"forty"}
y = {"1"=>"one", "2"=>"two",  "3"=>"tree"}
z = Hash.new

x.each_pair do |key1,value1|
  y.each_pair do |key2,value2|
    z[ (key1 + key2) ] = (value1+" "+value2)
  end
end

z.map{|k,v| "#{k}=#{v}"}.join(';  ')

 => "33=thirty tree;  22=twenty two;  23=twenty tree;  41=forty one;  42=forty two;  31=thirty one;  43=forty tree;  32=thirty two;  21=twenty one" 







No comments:

Post a Comment