I have 6 digits (1, 2, 3, 4, 5, 6), and I need to create all possible combinations (i.e. 6*5*4*3*2*1 = 720 combinations) in which no number can be used twice and O is not allowed. I would like to obtain combinations like: 123456, 246135, 314256, etc. Is there a way to create them with Matlab or R? Thank you.
-
Dupe for R: [Generating all distinct permutations of a list in R](http://stackoverflow.com/q/11095992/903061). `combinat::permn(1:6)` – Gregor Thomas Sep 20 '16 at 16:25
-
should we close this as dupe since it requests both R and MATLAB ? – Ben Bolker Sep 20 '16 at 16:27
-
1permutations in e1071 also work for numbers: `library(e1071)` `permutations(6)` – fabianegli Sep 20 '16 at 16:35
-
I'd feel good closing as a dupe if we found a matlab dupe as well. At a glance, I found many more specific permutation questions for matlab, but nothing that felt like a good fit. – Gregor Thomas Sep 20 '16 at 16:59
-
@Gregor I didn't find a good one for Matlab either. Anyway, in Matlab (perhaps in R as well but I don't know) this is a very basic question – Luis Mendo Sep 20 '16 at 17:10
4 Answers
In Matlab you can use
y = perms(1:6);
This gives a numerical 720×6 array y
, where each row is a permutation:
y =
6 5 4 3 2 1
6 5 4 3 1 2
6 5 4 2 3 1
6 5 4 2 1 3
6 5 4 1 2 3
···
If you want the result as a char array:
y = char(perms(1:6)+'0');
which produces
y =
654321
654312
654231
654213
654123
···

- 110,752
- 13
- 76
- 147
In R:
library(combinat)
p <- permn(1:6)
gives you a list; do.call(rbind, p)
or matrix(unlist(p), ncol=6, byrow=TRUE)
will give a numeric array; sapply(p,paste,collapse="")
gives a vector of strings.

- 211,554
- 25
- 370
- 453
Here's a base R
'solution':
p <- unique(t(replicate(100000, sample(6,6), simplify="vector")))
nrow(p)
#> [1] 720
head(p)
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 3 5 4 2 1 6
#> [2,] 6 3 5 4 1 2
#> [3,] 5 1 6 2 3 4
#> [4,] 6 5 3 2 4 1
#> [5,] 5 2 3 6 4 1
#> [6,] 1 4 2 5 6 3
It's a hack of course, and this potentially only applies to the example given, but sometimes it's useful to do things in silly ways... this takes an excessive number of samples (without replacement) of the vector 1:6
, then removes any duplicates. It does indeed produce the unique 720
results, but they're not sorted.

- 3,897
- 14
- 34
A base
R approach is
x <- do.call(expand.grid, rep(list(1:6), 6))
x <- x[apply(x, MAR = 1, function(x) length(unique(x)) == 6), ]
which creates a matrix with 6^6 rows, then retains only rows that contain all 6 numbers.

- 12,868
- 2
- 27
- 48