Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am stuck on the following problem. I want to find an algorithm that finds all possible permutations of a certain numbers of distinct digits and then put them in a large matrix for instance. For instance for the digits 0, 1 and 2 I want to get the matrix:

2 1 2 0 1 0
1 2 0 2 0 1
0 0 1 1 2 2

Here they are in order but this is not required per se. Does anyone know a nice algorithm to achieve this? Thanks in advance.

share|improve this question
    
Most languages have libraries that can do permutations for you - perl python ruby java - don't do work that is already done for you. –  MichaelT Apr 14 '13 at 1:58
add comment

1 Answer

Building on MichaelT's comment, here's an example solution in Python:

from itertools import permutations
for p in permutations(['0', '1', '2'], 3):
    print p

Output looks like this:

('0', '1', '2')
('0', '2', '1')
('1', '0', '2')
('1', '2', '0')
('2', '0', '1')
('2', '1', '0')

You'll have to arrange the output to match your desired format.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.