Created
February 17, 2011 21:18
-
-
Save Sharpie/832723 to your computer and use it in GitHub Desktop.
Lazy permutations
This file contains 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
require(itertools) | |
permutations <- function(iterable) { | |
# Returns permutations of iterable. Based on code given in the documentation | |
# of the `permutation` function in the Python itertools module: | |
# http://docs.python.org/library/itertools.html#itertools.permutations | |
n <- length(iterable) | |
indicies <- seq(n) | |
cycles <- rev(indicies) | |
stop_iteration <- FALSE | |
nextEl <- function(){ | |
if (stop_iteration){ stop('StopIteration', call. = FALSE) } | |
if (cycles[1] == 1){ stop_iteration <<- TRUE } # Triggered on last iteration | |
for (i in rev(seq(n))) { | |
cycles[i] <<- cycles[i] - 1 | |
if ( cycles[i] == 0 ){ | |
if (i < n){ | |
indicies[i:n] <<- c(indicies[(i+1):n], indicies[i]) | |
} | |
cycles[i] <<- n - i + 1 | |
}else{ | |
j <- cycles[i] | |
indicies[c(i, n-j+1)] <<- c(indicies[n-j+1], indicies[i]) | |
return( iterable[indicies] ) | |
} | |
} | |
} | |
# chain is used to return a copy of the original sequence | |
# before returning permutations. | |
return( chain(list(iterable), new_iterator(nextElem = nextEl)) ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment