This is a homework assignment for a first semester CS class, so I don't want to be spoon-fed an answer, but at least maybe pointed in the right direction.
The first part of the assignment asked us to write a function or functions that take as input a 4 digit phone number, and then displays all the possible letter combinations of on those buttons on the phone.
so, if you input 2345 you get:
ADGJ ADGK ADGL
ADHJ ADHK ADHL
ADIJ ADIK ADIL
AEGJ AEGK AEGL
etc etc etc.
Here's how I solved this part. I looped through the input string, and sent each individual char to a function that returned a string of those possible letters. So after that I have 4 strings:
word1 = "ABC"
word2 = "DEF"
word3 = "GHI"
word4 = "JKL"
Then I created 4 nested for loops to scroll through and print out all the combinations, like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
void displayPhoneWords(const string &word1, const string &word2
const string &word3, const string &word4)
{
for (unsigned int count1=0;count1<word1.length();count1++)
for (unsigned int count2=0;count2<word2.length();count2++)
for (unsigned int count3=0;count3<word3.length();count3++)
{
for (unsigned int count4=0;count4<word4.length();count4++)
{
cout << word1[count1] << word2[count2] ;
cout << word3[count3] << word4[count4] ;
} // for
cout << endl;
}
} // displayPhoneWords
|
I'm still too new to know if it's an elegant solution or a kludge, but it works.
The 'challenge' part of the assignment is to make this work for any arbitrary number of digits. Now I see that my solution is far to rigid to accomplish this, so I've scoured the text and web looking for a possible solution. It seems that I will need to use a recursive function(I think). All the examples I've looked at are pretty simple like doing factorials, where once the function reaches the base case and starts to return, it simply multiplies the base by the new value and keeps going.Too simple to be of use to me.
I realize I won't be able to use my vars word1,word2, etc, because I won't know at compile time how many digits there will be. I'm guessing I will have to create one string with all the letters like "ABCDEFGHIJKL" and then use some sort of a counter so that the function knows where one "phone button" stops and the next one starts.A problem with that is that the buttons 7 and 9 have 4 chars instead of 3.
Can someone maybe give me a place to start? Sorry if I'm too verbose, this is my first post and I wanted it clear that I've spent hours on this problem by myself before reaching out for some help.
Gary