tags:

views:

161

answers:

5

suppose n=3 then output should be: a vector containing vectors: 123 213 132 231 321

A: 

Here's some non-recursive code for this:

maxdepth <- 4
curdepth <- 1
l <- list()
i <- 0
while (i < maxdepth) {
    l <- c(l, 1)
    i <- i+1
}
done <- 0
results <- list()
resct <- 1

print(paste(sep=",",l))

while (curdepth > 0) {
    if (curdepth == maxdepth) {
        results[[resct]] <- l
        resct <- resct+1
        l[[curdepth]] <- l[[curdepth]]+1
    }
    if (l[[curdepth]] == maxdepth+1) {
        while (!done && l[[curdepth]] == maxdepth+1) {
            l[[curdepth]] <- 1
            curdepth <- curdepth-1
            if (curdepth == 0) {
                done <- 1
            }
        }
        if (!done) {
            l[[curdepth]] <- l[[curdepth]]+1
        }
    } else if (curdepth < maxdepth) {
        curdepth <- curdepth+1
    }
}

edit: made to output vector instead of printing; when done, "results" should contain the desired answer

Borealid
+5  A: 

This will solve your question:

install.packages("combinat")
require(combinat)
permn(1:3)

Also the functions: choose, combn ,expand.grid Might prove useful for you in the future.

Tal Galili
+1  A: 

The gregmisc package should have the permutations() function.

permutations3,3)
apeescape
Is it the same as gtools ?
Tal Galili
yes, older name before it was broken up into smaller pieces
John
+6  A: 
library(gtools)
permutations(3,3)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    2
[3,]    2    1    3
[4,]    2    3    1
[5,]    3    1    2
[6,]    3    2    1
gd047
Nicee solution gd.
Tal Galili
A: 

I don't know if it is the case, but I'll give it a try.
If you'd like to do something with huge number of permutations of a bit longer vectors, it is much less demanding and about as good to use Monte Carlo and simply sample the space with large number of random permutations (that might be generated in R with sample function).

mbq