Generating Combinations

 DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

#### Hybrid View

1. Registered User
Join Date
Oct 2004
Location
Chicago
Posts
108

## Generating Combinations

I have to make a program where the user inputs a number and display all the possible combinations of the letters representing the digits in the number.

I am not asking anyone to do this for me, but I simply don't know where to start with generating the different combinations. I am supposed to avoid using numbers with 0s and 1s

For example

2 - ABC
3 - DEF
4 - GHI
5 - JKL
6 - MNO
7 - PRS
8 - TUV
9 - WXY

835-555-3566

The only letter here that was changed here was the one representing 8

TDJ-JJJ-DJMNO
UDJ-JJJ-DJMNO
VDJ-JJJ-DJMNO

Does anyone have any ideas on how I can go about solving this problem?

2. Registered User
Join Date
Jul 2005
Location
SW MO, USA
Posts
299
One way would be to have an number of nested loops that iterate thru the 3 possible letters for each number. That would be an easy solution for a fixed number of digits in the number.
For a variable/not fixed number of digits, that will take some thought.

3. Registered User
Join Date
Oct 2004
Location
Chicago
Posts
108
I believe it will be for a set number of digits. I know I have to use nested loops, but I am not able to picture how they would work.

I know it would go throught the digits one at a time, and there would be three iterations for each digit, but doesen't there have to be another loop? That is what I don't know how to do

4. Senior Member
Join Date
Dec 2004
Location
San Bernardino County, California
Posts
1,468

http://www.merriampark.com/perm.htm

5. Registered User
Join Date
Jul 2005
Location
SW MO, USA
Posts
299
Use three arrays, one 10x3 to hold the chars for each digit:
char[][] val = new char[] { {}.{},
{A,B,C}
...
{W,X,Y}};

To use: val[2][0] would be the first char of 3 for "2"

Then an index array that holds the digits entered by the user:

int[] index = new int[nbrofdigits];
for example: index[0] = 8 and index[1] = 3 etc
then the iterations say using i0, i1 etc:

String = vals[index[0]][i0]+ vals[index[1][i1} ... + vals[index[last]][ix];

You want to create all possible combinations. Use base 3 indexes. You want the indexes to run from: 00...0 thru 22...2 base 3.
For example: 00000, 00001, 00002, 00010 etc
Use each digit as an index: ie 0,0,0,0,0 to 0,0,0,1,0 to the above arrays.

One way to generate this series is to count with an int and then convert it to base 3.
To convert an int base 10 to base 3, modulo and divide by 3 and modulo.

For example 26 base 10 = 222 base 3. 26%3 = 2; 26/3 % 3 = 2; 26/9 %3 = 2

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise