Last active
August 29, 2015 14:18
-
-
Save ahirschberg/2d218dfecfa497156ba8 to your computer and use it in GitHub Desktop.
Working lazy version of permutations using yield statements
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) | |
| # recursion's base case: return, not yield (outside of enumerator) | |
| return [list] if list.size == 1 | |
| en = Enumerator.new do |y| | |
| 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} # in case you're not familiar with ruby, the p keyword prints the output of an object's #inspect method | |
| 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", "d", "c"] | |
| ["a", "c", "b", "d"] | |
| ["a", "c", "d", "b"] | |
| ["a", "d", "b", "c"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment