Permutations: Difference between revisions

m
(→‎{{header|Haskell}}: Slight simplification, dropping a redundant import)
Line 5,401:
 
=={{header|R}}==
===Iterative version===
<lang r>next.perm <- function(p) {
<lang nr>next.perm <- lengthfunction(pa) {
in <- n - 1length(a)
ri =<- Tn
forwhile (i in> seq(n1 && a[i - 1,] 1)>= a[i]) {i <- i - 1
if (p[i] < p[i +== 1]) {
r = FNULL
} else break{
j <- ni
k <- n
while (j < k) {
x s <- pa[j]
p a[j] <- pa[k]
p a[k] <- xs
j <- j + 1
k <- k - 1
}
j s <- a[i +- 1]
p[ j] <- xi
while (pa[j] ><= p[i]s) j <- j -+ 1
p a[i - 1] <- pa[j]
a[j] <- j + 1s
# 1 2 3 a
}
j <- i + 1
k <- n
while (j < k) {
x <- p[j]
p[j] <- p[k]
p[k] <- x
j <- j + 1
k <- k - 1
}
if(r) return(NULL)
j <- n
while (p[j] > p[i]) j <- j - 1
j <- j + 1
x <- p[i]
p[i] <- p[j]
p[j] <- x
return(p)
}
 
print.permsperm <- function(n) {
pe <- 1:nNULL
xa <- p[i]1:n
while (!is.null(p)) {
repeat {
cat(p, "\n")
pe <- next.permcbind(pe, a)
a <- next.perm(a)
while if (!is.null(pa)) {break
}
unname(e)
}
# 3 2 1}</lang>
 
'''Example'''
print.perms(3)
# 1 2 3
# 1 3 2
# 2 1 3
# 2 3 1
# 3 1 2
# 3 2 1</lang>
 
<lang>> perm(3)
Here is another recursive version.
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 2 3 3
[2,] 2 3 1 3 1 2
[3,] 3 2 3 1 2 1</lang>
 
===Recursive version===
<lang r># 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))
1,336

edits