MATLAB Answers

how to create an array of all permutations

11 views (last 30 days)
antifreund
antifreund on 2 Jul 2020
Commented: James Tursa on 3 Jul 2020
Hi there,
I have a question about how to create the following array in a simple, concise way (for any permutations).
Think of a 4 digit lock, but numbers allowed are not 0-9, but 1-6 or 0-17 (or any other range).
For 0-9 there are 10^4 permutations, which should be a 10000 x 4 array, each row showing one of the permutations.
I thought of building the array from 4 vectors (thousand, hundred, tens, ones), but that is also cumbersome when looking at a 7digit lock with 11 possible numbers for each digit.
example:
4 digits, possible numbers for each digit 1 - 6 (1296 permutations)
unity_ones = [1;6];
which means that the ones vector can be created by:
n = 1296/6;
ones_vector = [];
for i=1:n
ones_vector = [ones_vector,ones];
end
Then one can do the same for the tens_vector, hundreds_vector and thousands_vector... This seems not very efficient. I am sure there is an easier, one or two liner out there.... :-)

  0 Comments

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 2 Jul 2020
If you want all of them in an array (which might be too large if the number of digits is too large), you can use
n = number of digits
b = range of the digits (0 to b)
result = dec2base(0:(b+1)^n-1,b+1);
This will give you a character array since the digits might be bigger than 9.
If b is 9 or less, you can turn this into numeric with
result = dec2base(0:(b+1)^n-1,b+1) - '0';
Otherwise, you would need code to convert the letters 'A' - whatever into numbers.

  3 Comments

antifreund
antifreund on 2 Jul 2020
Thanks for the answer James...
That works well for any number below 9, but still requires an additional conversion
n = 4
b = 5 %(6 digits)
result = dec2base(0:(b+1)^n-1,b+1);
yields:
result=
'0000'
'0001'
'0002'
'0003'
'0004'
'0005'
'0010'
'0011'
....
'6666'
How is that converted into an 1296 x 4 array with numbers?
Thanks for your help, much appreciated!
antifreund
antifreund on 2 Jul 2020
Yes, I know it is str2num to convert a string into a number, but ideally each row needs to be mae into 4 columns with one digit in each, then converting into a number ( or if it is a letter for a range being beyond 0-9, first replacing and then converting to a number...)
James Tursa
James Tursa on 3 Jul 2020
I already posted that. You simply do the - '0' operation at the end.

Sign in to comment.

More Answers (1)

madhan ravi
madhan ravi on 2 Jul 2020
doc randperm

  1 Comment

antifreund
antifreund on 2 Jul 2020
this seems to generate only one permutation without repeats... But for a 4 digit lock with permissible numbers 1-6 one would have 1296 permutation from:
0 0 0 0
to
6 6 6 6
The question is how to populate that array with 1296 unique rows?

Sign in to comment.

Products


Release

R2018b