Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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. – user40980 Apr 14 '13 at 1:58

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

Your Answer


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.