Ugh... Recursion question...

Status
Not open for further replies.

Ajis

Ars Praetorian
560
After learning a little about recursion, I've got an assignment to write a recursive procedure that will accept a phone number and return all the possible letter combinations (x^3). So if ListMnemonics("23") is called, it will give AD, AE, AF, BD, BE, BF, etc.

I've got a char array:
code:<HR>
Code:
char mnArr[9][3] = {" ","ABC","DEF","GHI","JKL","MNO","PRS","TUV","WXY"};
In which the array can be accessed as (x,y). Therefore keypad 3, first letter, is (2,0) "D". (Yes, if the user gives "3" the code subtracts 1 to get to the proper element in the array).

I have a function that will get a phone number (i.e. 1234567) and put it into an integer array (i.e {1,2,3,4,5,6,7} ) using malloc to determine the size of the array.

However, I have no idea where to begin using recursion to solve this problem or how it is involved when displaying the solution! :confused:

Thanks for any help!!
 
Okay buddy - since it seems nobody else is going to field this question - I'll take mercy upon you and show ya how its done :)

I wrote a quick sample function in VB.NET that uses recursion to output the data you requested. Here it is below:

Sub GenerateDigit(ByVal Pos As Integer, ByVal Number As String, Optional ByVal Chunk As String = "")
Dim Letters As String
Dim Counter As Integer
Dim Digit As Integer
Digit = CInt(Number.Chars(Pos).ToString)
If Counter = 0 Then Counter = 1
Select Case Digit
Case 1, 0
Letters = ""
Case 2
Letters = "ABC"
Case 3
Letters = "DEF"
Case 4
Letters = "GHI"
Case 5
Letters = "JKL"
Case 6
Letters = "MNO"
Case 7
Letters = "PQRS"
Case 8
Letters = "TUV"
Case 9
Letters = "WXYZ"
End Select
For Counter = 1 To Letters.Length
If Pos = Number.Length - 1 Then
If TxtOutput.Text <> "" Then
TxtOutput.Text = TxtOutput.Text & vbNewLine
Application.DoEvents()
End If
TxtOutput.Text = TxtOutput.Text & Chunk & Letters.Chars(Counter - 1).ToString
Else
GenerateDigit(Pos + 1, Number, Chunk & Letters.Chars(Counter - 1).ToString)
End If
Next
End Sub
Since its in VB - it should be easy enough to comprehend. If you want more explanation - just post a question and I will get around to answering it sooner or later.

J
 

dmcnaught

Ars Scholae Palatinae
684
I'll give you a hint to get started:

When writing a recursive function, you need to break it down into the "base case(s)" and the "recursive case(s)". The former you can solve without making a recursive call. The latter involve breaking up the problem, and making a recursive call on a simplified part of it.

So what would your base case and recursive case be for this problem?
 
I would have to say that recursion is one of those concepts that can take you a lifetime to master. You can get a good feel for it - but I've yet to meet anybody who can create a recursive routine off the top of their head without thinking about it.

The great thing about recursion is that it really can lessen the amount of code it takes to perform a complex activity. I think the real challenge in your assignment would be trying to write a program that would do this without recursion.

J
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by darkgamorck:
I would have to say that recursion is one of those concepts that can take you a lifetime to master.

It could, but it need not. When presented well, it should only take students a couple of lectures, whether or not they have seen iteration previously.

You can get a good feel for it - but I've yet to meet anybody who can create a recursive routine off the top of their head without thinking about it.

There are lots of us.

Ajis, I think your instructor is so bungling the job of teaching recursion that it's no wonder you aren't getting it. Don't panic. dmcnaught's advice is good. Otherwise, it's hard to give you any constructive help without knowing something about the constraints of your problem.

(kg*m*m)/(s*s)
 

Ajis

Ars Praetorian
560
So what would your base case and recursive case be for this problem?

The base case would be when the last option is given. In the array I gave and using the numbers "23" as input, CF would be the last possible option. Numerically, that is when all numbers are at their last letter (for "23" and the char array I gave earlier, that would be (1,2),(2,2) ). The recursive case? Well... I can't figure out how to reduce it. I've got pages of notes and doodles, but I'm lost.

BTW, This class is using C. I've never touched Basic. ;)
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by reboot:
Too many if you ask me. :D

Not enough if you ask me :(

Most of the people I've met who have difficulty "thinking" recursively or "getting" recursion don't have any problem with self-referential linked data structures. It doesn't faze them that the definition of a linked list must, of necessity refer to the definition of a linked list:

code:<HR>
Code:
struct list_node {
    data_t            data;
    struct list_node* next;
};

So, when we write functions acting over this inductively (yeah, that's fancy) defined data, we should expect them to be recursive. The functions should refer to their own definitions in exactly the same places that the data referred to its own definition.

Unfortunately, recursion is rarely taught as if it were a natural consequence of self-referential data structures. Instead, we get crap like factorial and fibonacci. Factorial (recursion over the natural numbers) is recursive not because the natural numbers are implemented inductively, but because they are isomorphic to an inductive datatype. Fibonacci is recursive not because fibonacci numbers themselves are represented inductively, but because they are isomorphic to a particular kind of tree structure.

It's stupid to expect students to understand the screaming simplicity and incredible naturalness of recursion when it is hidden behind a complicated and artificial (seeming) isomorphism. Stupid, stupid, stupid.

Here's the problem, Ajis. You are trying to recur over an array (or a string, depending on how you write the program). Arrays (and strings) are not defined or implemented in terms of themselves (in C or C++). You have to find a way to think of them as if they were, but that in itself is an artificial approach.

Here's another problem. Only somebody on crack would recur over an array or string in a C or C++ program. If you follow the philosophy that "data structures suggest (or determine?) algorithms", then an array or a string would lead you naturally to a loop.

It is possible to recur over that array, but it requires some technical sophistication (not a lot, but more than you seem to have (and that's not your fault, either)) and an unnatural view of what's going on. I think I could probably walk you from where you are to an understanding of a correct solution, but there would be many steps along the way, and many leaps of faith.

Instead, it should be your instructor's job to walk you along that path, by starting with the simplest, most obvious problem and leading you to a belief that there isn't anything difficult about recursion at all.

Alas, now I'm ranting. :oops:

(kg*m*m)/(s*s)
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by Ajis:
The base case would be when the last option is given. In the array I gave and using the numbers "23" as input, CF would be the last possible option. Numerically, that is when all numbers are at their last letter (for "23" and the char array I gave earlier, that would be (1,2),(2,2) ). The recursive case? Well... I can't figure out how to reduce it. I've got pages of notes and doodles, but I'm lost.

OK, you've got a start. It's not right, but it's a start, and that's good :)

Your function ListMnemonics takes a string. Let's stop and think about the structures of strings for a second. Is there any way you can think of a string as being made up of smaller strings? Because in order to recur over a string, you've got to think of strings as being made of strings.

One way is that you could think of a long string like "1234567" as a pair of a character '1' and a shorter string "234567". Likewise, your string "23" is a pair of '2' and "3", which in turn is a pair of '3' and "".

Is this useful? Let's say I give you a string. Can you tell me if it's empty? If it's not empty, can you tell me the first character in it? If it's not empty, can you tell me the substring that remains if you "drop" the first character?

Now, what's the shortest possible string (careful, this could be tricky!). What's the shortest string you want "ListMnemonics" to work on? How can you check if the input has this length? If it does, what's the answer (forget recursion here).

When you've got all that, come back for more, and somebody will tell you the magic secret step!

(kg*m*m)/(s*s)
 
Originally posted by newton_meter:
Is this useful? Let's say I give you a string. Can you tell me if it's empty? If it's not empty, can you tell me the first character in it? If it's not empty, can you tell me the substring that remains if you "drop" the first character?

Okay... That makes sense!
code:<HR>
Code:
int ListMnemonics(int x)
{
    int foo;

    if (mnArr == NULL)       // Can I do that?  NULL?
        return 0;            // exit the function if no more numbers.
    foo = x  % 10;           // but this will only get the last number, right, not the first?
    x = x / 10;              // chops off the digit now in foo.
    (do whatever with foo to get ABC, etc.);
    return (ListMnemonics(x));

I'm starting to understand... But tell me if I'm going in the wrong direction!

Thank everyone for so much help!! :)
 
I'm not quiting the assignment by any means (that was 1 of 5 questions though and we were only given one week to do them). But we aren't allowed to turn anything in late.

I plan to keep re-reading the chapter until I understand it, but he's already gone to ADT stacks or something or another... I couldn't remember, I was too busy trying to do recursion. ;)

... This is supposedly the second course in C-programming. But we certainly aren't picking up where we left off last semester (same instructor too!).
 

Aeirould

Ars Tribunus Angusticlavius
7,535
Subscriptor
Ajis:

I'm gonna lay all the concepts out on the line here. The others are baby stepping, and while that has its place (no offense to you guys) it's not my style.

What you want to define for a recursive function is:

1) What is the series you need to generate?

For you, that's AD, AE, AF, BD, BE, BF, CD, CE, CF for an input of "23". This ordering is not randomly chosen - look at it in detail.

If I passed "2", I get A, B, and C. If I passed "22", I'd get AA, AB, AC, BA, BB, BC, CA, CB, CC.

2) What is the atomic function you need?

For each number, I need to give the three (or four) letters that go with that number, combined with the results for this function for the next number, comined with the results for this function for the next number, etc.

3) How do you terminate (know that you've reached the end?) at root level?

In your case, it's pretty easy. If you run out of numbers in your passed string, (if the passed string is 1 char in length), you do not need to recurse anymore, you can return.

So, "drawing" a tree:

Pass 234

Function recieves 234

-Operational length is > 1, so call self with 34

--Operational length is >1, so call self with 4

---Operational length is 1. grab your letters.

---Return your letters(combinations)

--Recieved input from lower function, remaining operational length is 1. Grab your letters and permute with result.

--Return your combinations(letters)

-Received input from lower function, remaining operational length is 1. Grab your letters and permute with result.

-Return your combinations(letters)

You have your answer in that last return.

So, what you need to build are:

Data structure to map numbers to letters.

Routine to permute one list with another:
(Input ABC and AA AB AC, return AAA AAB AAC BAA BAB BAC CAA CAB CAC) - a nested while or for will handle this nicely)

Recursive function itself.

Mostly, I do these steps without breaking it down, so I may well have skipped a step or two. If so, I apologize. I don't plan on actually writing this for you, though, and I hope noone else takes that step. You should still code this one out for the experience in doing it, imho.
 
Status
Not open for further replies.