Guest User

Untitled

a guest
Mar 19th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.56 KB | None | 0 0
  1. #Permutations Recursive
  2.  
  3. def _add_head(head, res)
  4. out = []
  5. res.each do |permutation|
  6. 0.upto(permutation.length) do |i|
  7. _insert!(i, head, permutation, out)
  8. end
  9. end
  10. out
  11. end
  12.  
  13. def _insert!(i, head, permutation, out)
  14. if i == 0
  15. out << [head, *permutation[0..-1]]
  16. elsif permutation[i] == nil
  17. out << [*permutation[0..-1], head]
  18. else
  19. out << [*permutation[0...i], head, *permutation[i..-1]]
  20. end
  21. end
  22.  
  23. def permutations(res)
  24. return [res] if res.length == 1
  25. _add_head(res[0], permutations(res[1..-1]))
  26. end
  27.  
  28. print permutations([1,2,3,4])
Add Comment
Please, Sign In to add comment