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

12 lines
407 B
R
Raw Permalink Normal View History

2019-09-12 10:33:56 -07:00
# list of the vectors by inserting x in s at position 0...end.
linsert <- function(x,s) lapply(0:length(s), function(k) append(s,x,k))
2017-09-23 10:01:46 +02:00
2019-09-12 10:33:56 -07:00
# list of all permutations of 1:n
perm <- function(n){
if (n == 1) list(1)
else unlist(lapply(perm(n-1), function(s) linsert(n,s)),
recursive = F)}
2017-09-23 10:01:46 +02:00
2019-09-12 10:33:56 -07:00
# permutations of a vector s
permutation <- function(s) lapply(perm(length(s)), function(i) s[i])