Advertisement
heroofhyla

Finding arbitrary permutations of a list

Oct 26th, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.68 KB | None | 0 0
  1. def factorial(n)
  2.   num = 1
  3.   for i in 1..n do
  4.     num *= i
  5.   end
  6.   num
  7. end
  8.  
  9. def permutation(list, n)
  10.   if n < 0
  11.     raise "Index must be positive"
  12.   end
  13.  
  14.   working = Array.new(list)
  15.   n = n%factorial(working.length)
  16.  
  17.   index = 0
  18.   for i in (working.length-1).downto(1) do
  19.     pos = n/factorial(i)
  20.     n = n%factorial(i)
  21.     tmp = working[index]
  22.     working[index] = working[index+pos]
  23.     working[index+pos] = tmp
  24.     index += 1
  25.   end
  26.   return working
  27. end
  28.  
  29. puts "Enter a list of values."
  30. values = gets.chomp.split(/[ ]*[ ,][ ]*/)
  31.  
  32. puts "All possible permutations:"
  33. for index in 0...factorial(values.length) do
  34.   print "#{permutation(values,index)}\n"
  35. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement