Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def factorial(n)
- num = 1
- for i in 1..n do
- num *= i
- end
- num
- end
- def permutation(list, n)
- if n < 0
- raise "Index must be positive"
- end
- working = Array.new(list)
- n = n%factorial(working.length)
- index = 0
- for i in (working.length-1).downto(1) do
- pos = n/factorial(i)
- n = n%factorial(i)
- tmp = working[index]
- working[index] = working[index+pos]
- working[index+pos] = tmp
- index += 1
- end
- return working
- end
- puts "Enter a list of values."
- values = gets.chomp.split(/[ ]*[ ,][ ]*/)
- puts "All possible permutations:"
- for index in 0...factorial(values.length) do
- print "#{permutation(values,index)}\n"
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement