Reputation: 692
I am working on a problem in which I am given a number and need to
find every possible permutation of the digits in that number. For
example, if I am given 20
, the answer would be: 20
and 02
. I know
that there are n!
possible permutations, and I have divided up the
numbers so that each digit is an element in an array. My question is:
How can I loop through this array to generate every possible
combination of a number that is at least 2 digits long but no more
than 6.
Upvotes: 1
Views: 6913
Reputation: 23680
Say the n
individual digits are in an array of length n
. Then the problem of generating the permutations boils down to:
n
digits as the first digit to print.n-1
digits.A recursion.
The pseudocode for such a recursive function permute
would be something like:
List permute (Array digits)
{
List permutations = /* initialize an empty list */
for (i=0; i<n; i++)
{
firstDigit = digit[i];
Array otherDigits = /* array containing all digits except firstDigit. */
List subPermutations = permute(otherDigits);
/* prepend firstDigit into each element of 'subPermutations' */
/* add all elements of 'subPermutations' to the list 'permutations' */
}
return permutations;
}
Then simply call permute
and print out the list, or do whatever else with it.
EDIT: You also need to handle the edge case of permute
ing 1 digit.
I think this is already too much information for 'homework' :)
Upvotes: 2
Reputation: 78324
Hint:
How would you solve this problem for a 1-digit number ?
Now, how would you solve this problem, given that you have the answer to the previous question, for a 2-digit number ?
Upvotes: 5