Skip to content

Instantly share code, notes, and snippets.

@brezniczky
Created June 28, 2016 21:46
Show Gist options
  • Save brezniczky/684f9e29e57b535aa8e7eabb9e7ee9fa to your computer and use it in GitHub Desktop.
Save brezniczky/684f9e29e57b535aa8e7eabb9e7ee9fa to your computer and use it in GitHub Desktop.
How to generate all permutations of some numbers with a low heap allocation and without try-fail
get.perm = function(n, FUN = print) {
perm = n:1
switch_loop = function(L) {
# evaluate all pair exchanges on the given level (L)
if (L == 1)
FUN(perm)
else {
switch_pair = function(i1, i2) {
temp = perm[i1]
perm[i1] <<- perm[i2]
perm[i2] <<- temp
}
for(i in 1:L) {
if (i > 1)
# switch to involve something new from level L
switch_pair((i - 1), L)
# allow lower level items to vary
switch_loop(L - 1)
if (i > 1)
# switch back
switch_pair((i - 1), L)
}
}
}
switch_loop(n)
}
perms = c()
get.perm(5,
FUN = function(perm) perms <<- rbind(perms, perm))
print(perms)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment