RosettaCodeData/Task/Permutations/R/permutations-1.r

36 lines
522 B
R
Raw Permalink Normal View History

2019-09-12 10:33:56 -07:00
next.perm <- function(a) {
n <- length(a)
i <- n
while (i > 1 && a[i - 1] >= a[i]) i <- i - 1
if (i == 1) {
NULL
} else {
j <- i
k <- n
while (j < k) {
s <- a[j]
a[j] <- a[k]
a[k] <- s
j <- j + 1
k <- k - 1
2016-12-05 22:15:40 +01:00
}
2019-09-12 10:33:56 -07:00
s <- a[i - 1]
j <- i
while (a[j] <= s) j <- j + 1
a[i - 1] <- a[j]
a[j] <- s
a
2016-12-05 22:15:40 +01:00
}
2013-04-10 23:57:08 -07:00
}
2019-09-12 10:33:56 -07:00
perm <- function(n) {
e <- NULL
a <- 1:n
repeat {
e <- cbind(e, a)
a <- next.perm(a)
if (is.null(a)) break
2016-12-05 22:15:40 +01:00
}
2019-09-12 10:33:56 -07:00
unname(e)
2013-04-10 23:57:08 -07:00
}