Last active
August 29, 2015 14:18
-
-
Save ahirschberg/98f20a43b88895680055 to your computer and use it in GitHub Desktop.
Non-working lazy version of permutations.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def permutations_lazy(list) | |
| # return [list] if list.size == 1 | |
| en = Enumerator.new do |y| | |
| if list.size == 1 | |
| # yield instead of returning in the base case of recursion | |
| y.yield list | |
| end | |
| list.each do |locked| | |
| puts "locking #{locked}" | |
| list_copy = list.dup | |
| list_copy.delete locked | |
| permutations_lazy(list_copy).each do |permutation| | |
| puts "permutation #{permutation}, locked #{locked}" | |
| y.yield permutation.insert(0, locked) | |
| end | |
| end | |
| end | |
| en | |
| end | |
| if __FILE__ == $0 | |
| pl = permutations_lazy %w[a b c d] | |
| pl.first(5).each {|i| p i} | |
| end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Output: | |
| ["a", "b", "c", "d"] | |
| ["a", "b", "c", "a", "b", "c", "d"] | |
| ["a", "b", "c", "a", "b", "c", "a", "b", "c", "d"] | |
| ["a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "d"] | |
| ["a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "d"] | |
| My best guess for why this happens is that because the base case is yielding and not returning, the algorithm never exits, and simply adds the locked values over and over again with each solution. This is just a guess, though. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment