Random Permutation in Ruby

Posted by sbecker Tue, 05 Jun 2007 23:41:00 GMT

This post on Algo Blog about random permutation shows a cool a little algorithm for randomizing an array which apparently impresses interviewers. I thought it might be fun to write it in Ruby:

def permute_array(a)
  1.upto(a.length - 1) do |i|
    j = rand(i + 1)
    a[i], a[j] = a[j], a[i]
  end
  a
end

# alternate version
def permute_array2(a)
  0.upto(a.length - 2) do |i|
    j = rand(a.length - i)
    a[i], a[j] = a[j], a[i]
  end
  a
end

This is actually a pretty fun little function to use. For example – to find all the unique possible combinations of letters in my name: (Secret Scrabble weapon)

# Generate an array of 5000 randomized versions of the letters 
# used in my name. Filter out the unique ones and sort it. 
# Did I really need to comment this?

(1..5000).map{ permute_array("scott".split("")).join }.uniq.sort

=> ["costt", "cotst", "cotts", "csott", "cstot", "cstto", "ctost", 
"ctots", "ctsot", "ctsto", "cttos", "cttso", "ocstt", "octst", 
"octts", "osctt", "ostct", "osttc", "otcst", "otcts", "otsct", 
"otstc", "ottcs", "ottsc", "scott", "sctot", "sctto", "soctt", 
"sotct", "sottc", "stcot", "stcto", "stoct", "stotc", "sttco", 
"sttoc", "tcost", "tcots", "tcsot", "tcsto", "tctos", "tctso", 
"tocst", "tocts", "tosct", "tostc", "totcs", "totsc", "tscot", 
"tscto", "tsoct", "tsotc", "tstco", "tstoc", "ttcos", "ttcso", 
"ttocs", "ttosc", "ttsco", "ttsoc"]