Advertisement
Guest User

Untitled

a guest
Sep 1st, 2015
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.42 KB | None | 0 0
  1. def myproduct(*arrays)
  2. return [] if arrays.empty?
  3. return arrays[0].collect{|elem| [elem]} if arrays.size == 1
  4.  
  5. head = arrays[0]
  6. tail = arrays.drop(1)
  7.  
  8. head.inject([]) do |x1,y1|
  9. myproduct(*tail).inject(x1) do |x2,y2|
  10. x2 << [y1] + y2
  11. end
  12. end
  13. end
  14.  
  15. p myproduct([1,2],[3,4]) # => [[1, 3], [1, 4], [2, 3], [2, 4]]
  16. p myproduct([1],[2,3,4]) # => [[1, 2], [1, 3], [1, 4]]
  17. p myproduct([1,2],[3,4],[]) # => []
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement