473,386 Members | 1,828 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Recursion...Its hard to grasp. Help.

So I have my Algorithms class tonight and I want to get the lab done before or during the class. I have write a recursive method that takes an int as a parameter and also returns an int. It has to REVERSE the int. What the heck. I'm not allowed to convert it to a string or anything, it says that I will not get credit if I do. So could someone give me some hints? The only thing I've gotten so far is the main method that accepts an int from the user and the call to the reverse() method which hasn't even been written yet. K thx.
Jan 27 '09 #1
27 2776
JosAH
11,448 Expert 8TB
Are two (recursive) methods allowed? If so, think of a number as HD where H is the number without the last digit D and D is the last digit. You want to reverse H and prepend the single digit D to it. This means that you have to multiply D by a power of ten depending on the magnitude of H.

Here's part of the spoiler:

Expand|Select|Wrap|Line Numbers
  1.     private static int pow(int i) {
  2.  
  3.         return (i < 10)?1:10*pow(i/10);
  4.     }
  5.  
kind regards,

Jos
Jan 27 '09 #2
Thanks Joe! It will take a while for me to fully comprehend what you just wrote, but I'm going to print it out and refer to it whilst I write the method. I have a good deal of freedom as far as writing the method goes so I dont see why I couldn't use two. As long as I'm not converting it to a string ha! Thanks again Joe. If anyone else has any more suggestions please post!
Jan 27 '09 #3
Okay so I'm feeling really good about myself right now. I got the program to work fairly well. HOWEVER...dot dot dot...the reverse1() method is supposed to eliminate any zero's. For example, 1024 should become 421. But I cant think of a way to do this. Anyone have any ideas? I have until next Tuesday to figure it out.

Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. public class Reverser
  5. {
  6.     public static void main(String args[])
  7.     {
  8.         Scanner kbd=new Scanner(System.in);
  9.         int num;
  10.  
  11.         System.out.print("Enter a value to be reversed: ");
  12.         num=kbd.nextInt();
  13.  
  14.         System.out.println(reverse1(num));
  15.         System.out.println(reverse2(num));
  16.     }
  17.  
  18.     public static int reverse1(int a)
  19.     {
  20.         if (a%10==0)
  21.             return reverse1(a/10);
  22.         if (a<10)
  23.             return a;
  24.         else
  25.             return (int)Math.pow(10,(int)Math.log10(a))*(a%10)+reverse1((int)a/10);
  26.     }
  27.  
  28.  
  29.     public static int reverse2(int a)
  30.     {
  31.         if (a<10)
  32.             return a;
  33.         else
  34.             return (int)Math.pow(10,(int)Math.log10(a))*(a%10)+reverse2((int)a/10);
  35.     }
  36. }
Jan 28 '09 #4
JosAH
11,448 Expert 8TB
There's no need to use those logarithms and power methods; Think of a number as a sequence of digits. When you remove the digit on the right side you add it to the right off another number; when there are no more digits left the new number represents the reverse of the original number; an example:

num: 345 rev: 0 -> num: 34 rev: 5 -> num: 3 rev: 54 -> num: 0 rev: 543

Your additional constraint forbids a zero to be shifted in at the reverse of the number; the code will be three lines: one for the sentinel case, one for the zero check and one for the normal case.

kind regards,

Jos
Jan 28 '09 #5
Thanks again Jos! When I get back from work I will try to do that. It seems simple enough :).
Jan 28 '09 #6
I think you are doing it wrong. From what i understand what is important in this excercise is the recursion. As it is the reversing of digits i think the goal is to have one method do it all.

Take a look at this simple example with a global counter. In this counter you would have to put the length of the int.

Expand|Select|Wrap|Line Numbers
  1. void method( int counter){
  2.      if(counter == 0){
  3.          //Spot where you return the reversed int
  4.          return reversed;
  5.      }
  6.      else {
  7.         //This if should be for the handling of any zeros.
  8.         if(something == 0){
  9.            method(--counter);
  10.         }
  11.         else{
  12.            //Reverse 1 digit here
  13.            method(--counter);
  14.            return;
  15.         }
  16.      }
This is what i understood from your exercise, correct me if i am wrong.

Good luck,

BSCode266
Jan 31 '09 #7
Thanks BSCode, I was still having problems getting reverse1() to work, and I think you just helped a lot.
Jan 31 '09 #8
JosAH
11,448 Expert 8TB
@first2drown
Show us your attempt(s) so we can comment on it.

kind regards,

Jos
Jan 31 '09 #9
Jos, I would show you what I wrote if I had saved any changes to the code that I made Thursday night in Lab. I'm VERY new to this programming thing. I love it, but some concepts are still hard for me to grasp. Let me show you the actual assignment: http://www.midlandstech.edu/edu/ed/i...n/283/hw3.html

He extended the deadline, so I can work on it on Tuesday and Thursday during lab. The thing is...even my teacher can't figure it out and its incredibly discouraging. I'm actually the one who figured out how to get reverse2() working before anyone else...I had to show the teacher.

And when I was trying to implement what you told me to do Jos, I was having problems, not sure why exactly, I just couldn't get any of the output that I wanted. I spent most of my day Thursday trying to come up with some sort of algorithm to get it done. Definitely not saying that what you said is wrong, just that I lack the experience to implement it :( . So my code is nearly exactly the same as it was in my previous post except now it has NOTHING coded for reverse1().
Jan 31 '09 #10
And after reading your post again I got an idea, so I'm gonna try that right now.
Jan 31 '09 #11
Yeah still couldn't figure it out.
Jan 31 '09 #12
JosAH
11,448 Expert 8TB
Here goes: we want to reverse a bunch of digits; reread my previous reply: for a number num we remove the rightmost digits and shift it in another number that builds up the reverse; e.g. num: 3456, rev: 0; after one step we have num: 345 and rev: 6; after another step we have num: 34, rev: 65; a third step: num: 3, rev: 654 and a last step: num: 0, rev: 6543.

An additional constraint (so you told us) is that we don't want to shift in zeros in our (partially completed) reversed number.

In code: let the number num and the reversed number rev be the parameters to the (recursive) method:

Expand|Select|Wrap|Line Numbers
  1. int reverese(int num, int rev) { ... }
  2.  
If num < 10 we're ready, i.e. we either shift it in the rev number from the right if it isn't zero or we simply return the reversed number:

Expand|Select|Wrap|Line Numbers
  1. int reverse(int num, int rev) {
  2.    if (num < 10) return (num == 0)?rev:10*rev+num;
  3.    ...
  4. }
  5.  
otherwise we either shift the rightmost digit to the reversed number if it isn't zero, else we simply forget about it:

Expand|Select|Wrap|Line Numbers
  1. int reverse(int num, int rev) {
  2.    if (num < 10) return (num == 0)?rev:10*rev+num;
  3.    if (num%10 == 0) return reverse(num/10, rev);
  4.    return reverse(num/10, 10*rev+num%10);
  5. }
  6.  
The above code does what the story is all about: shift in any non-zero digit; keep on going when there are more digits (num >= 10) or we're done. The story to explain this all is much larger then the method itself (as often happens with recursive methods).

Try to chop down this little method so that it does shift in zeros and try to understand what it does in those three lines.

kind regards,

Jos
Jan 31 '09 #13
Okay wow. I actually get it now. I added your code to my program, modified it so it could compile, then ran it in debug mode so I could see exactly how it worked. The problem I was having understanding it was the 2nd int parameter in the method. I feel like I tried everything except that. Also, it helped me learn how to use those ?:; statements, for some reason we didn't go over those in class. My final code:


Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. public class Reverser
  5. {
  6.     public static void main(String args[])
  7.     {
  8.         Scanner kbd=new Scanner(System.in);
  9.         int num;
  10.           int shortenedNum;
  11.           int counter=0;
  12.           boolean shortened = false;
  13.  
  14.         System.out.print("Enter a value to be reversed: ");
  15.         num=kbd.nextInt();
  16.  
  17.  
  18.         System.out.println(reverse1(num,0));
  19.         System.out.println(reverse2(num));
  20.     }
  21.  
  22. public static int reverse1(int a, int rev) {
  23.     if (a < 10){
  24.         if (a == 0)
  25.             return rev;
  26.         else
  27.             return 10*rev+a;
  28.         }
  29.  
  30.       if (a%10 == 0)
  31.         return reverse1(a/10, rev);
  32.  
  33.     return reverse1(a/10, 10*rev+a%10);
  34.  
  35.    }
  36.  
  37.     public static int reverse2(int a)
  38.     {
  39.         if (a<10)
  40.             return a;
  41.         else
  42.             return (int)Math.pow(10,(int)Math.log10(a))*(a%10)+reverse2((int)a/10);
  43.     }
  44. }
  45.  
Jan 31 '09 #14
Also, let me know if you see something wrong with this? Instead of the original reverse2 method.

Expand|Select|Wrap|Line Numbers
  1. public static int reverse3(int a, int rev)
  2.       {
  3.          if (a < 10)
  4.             return 10*rev+a;
  5.          return reverse1(a/10, 10*rev+a%10);
  6.       }
  7.    }
Jan 31 '09 #15
Well reverse3 isn't recursive. It is making a call to reverse1. For it to be recursive it should call itself.

Expand|Select|Wrap|Line Numbers
  1. return reverse1(a/10, 10*rev+a%10);
A little sidenote, you really should try to avoid using variables with names like "a", "b", "c". Name them to the thing they represent just like Jos did, call it "num". Now your code is small but if you develop this as a habbit you are going to be in a world of hurt later.

Greets,

BSCode266
Feb 1 '09 #16
Nepomuk
3,112 Expert 2GB
When looking at Jos' last answer, it can be reduced - I have a running solution that has only 2 lines. Just let the recursive method take 2 inputs and think about the various things, that could happen: Is it done? If so, what should the output be? If not, what should be done with the inputs? You should be using % and / operators of course.

Oh, and no pow method is needed - I just use a simple *10 here and then.

Greetings,
Nepomuk
Feb 1 '09 #17
JosAH
11,448 Expert 8TB
Why don't you simply show your code; this thread has been a give away after all.

kind regards,

Jos
Feb 1 '09 #18
Nepomuk
3,112 Expert 2GB
Guess you're right. OK, here's my reverse function:
Expand|Select|Wrap|Line Numbers
  1. private static int reverse(int given, int done) {
  2.     if(given < 10) return (done*10+given);
  3.     else return reverse(given/10,((given%10==0) ? done : (done*10+given%10)));
  4. }
I've added a few extra brackets, just to make the way it works more clear. Of course, you can always remove them, if you like. Oh, and if you want to give only one argument, you can always overload the method with
Expand|Select|Wrap|Line Numbers
  1. private static int reverse(int num) {return reverse(num,0);}
Greetings,
Nepomuk
Feb 1 '09 #19
JosAH
11,448 Expert 8TB
@Nepomuk
You rewrote the if-then-else of lines #2 and #3 as a ternary expression. Not so intuitive is that the test for (given == 0) in line #1 is superfluous. It took me a bit of thinking (<-- that hurts! ;-) to understand it.

We could rewrite the entire thing as one big ugly line by using the ternary ?: expression again ...

kind regards,

Jos
Feb 2 '09 #20
Nepomuk
3,112 Expert 2GB
@JosAH
Jup, looks much nicer that way, doesn't it? ^^ @JosAH
Well, I thought I'd just reduce the amount of recursions. :D
@JosAH
Sure:
Expand|Select|Wrap|Line Numbers
  1. private static int r(int g,int d){return(g<10?d*10+g:r(g/10,g%10==0?d:d*10+g%10));}
will do the job just fine! ^^

Mind you, all of the solutions are tail recursive - isn't that beautiful? :-D Oh, and I just realised, that my solution isn't quite perfect - it doesn't work for negative numbers. So make that
Expand|Select|Wrap|Line Numbers
  1. private static int r(int g,int d){return((g>=0?g<10:g>-10)?d*10+g:r(g/10,g%10==0?d:d*10+g%10));}
(Math.abs() is SO overrated! ;-) )

Greetings,
Nepomuk
Feb 2 '09 #21
JosAH
11,448 Expert 8TB
@Nepomuk
There was no recursion involved in line #1, just a superfluous test. Your version doesn't reduce the amount of recursive steps; both versions take n steps where n is the number of digits in the number to be reversed.

@Nepomuk
Sure, all it does is chew off the rightmost digit and process it. It'd be more difficult not to implement tail recursion here. btw. Java version 7 has much better tail recursion removal; I like that, together with memoization those things can really speed up execution of it all and allows you to write functions in a more intuitive way.

kind regards,

Jos
Feb 2 '09 #22
I am not even close to you guys skill level, but isn't one important thing of writing code keeping it readable?

Greets,

~BSCode266
Feb 2 '09 #23
JosAH
11,448 Expert 8TB
@BSCode266
No, and readability is in the eye of the author anyways, so :-P
Remember: if it were hard to write it is supposed to be hard to read.

kind regards,

Jos ;-)
Feb 2 '09 #24
Thank all of you so much for the help. In my last post about reverse3() i meant to edit it to be recursive.

Expand|Select|Wrap|Line Numbers
  1. public static int reverse3(int a, int rev) 
  2.       { 
  3.          if (a < 10) 
  4.             return 10*rev+a; 
  5.          return reverse3(a/10, 10*rev+a%10); 
  6.       } 
  7.    }
I tested it and this code does work. I went ahead and submitted the final version to the teacher along with comments on how it works! That was certainly a learning experience.
Feb 4 '09 #25
JosAH
11,448 Expert 8TB
@first2drown
That version does copy the zero digits into the reverse of the number; you wrote that you didn't want that.

kind regards,

Jos
Feb 4 '09 #26
Well in reverse2() you do want to keep the 0s, but we used the Math.pow() method to do it, I was just testing reverse3() as a replacement to reverse2(). =D There were supposed to be 2 methods in my program, one that takes out the 0s and reverses, and one that reverses and keeps the 0s.
Feb 4 '09 #27
JosAH
11,448 Expert 8TB
@first2drown
Ok, I must've missed that part; problem solved then.

kind regards,

Jos
Feb 4 '09 #28

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Peri | last post by:
I'm trying to create Python parser/interpreter using ANTLR. Reading grammar from language refference I found: or_expr::= xor_expr | or_expr "|" xor_expr For me it looks like infinite recursion....
10
by: Christopher T King | last post by:
Is it feasable, and/or desirable to have Python optimize tail-recursive calls, similar to Scheme and gcc -O2? i.e. effectively compile this: def foo(n): return foo(n-1) into this: def...
12
by: Andrew Edwards | last post by:
Gentlemen, I have a Binary Search Tree ADT that should use recursion for all operation except for isEmpty() and isFull(); I have completed the insert function, and after inserting the numbers...
12
by: da Vinci | last post by:
Greetings. I want to get everyone's opinion on the use of recursion. We covered it in class tonight and I want a good solid answer from people in the "know" on how well recursion is accepted...
4
by: Dan | last post by:
I've encountered some strange behavior in a recursive procedure I'm writing for a bill of materials. First let me ask directly if what I think is happening is even possible: It seems like the...
43
by: Lorenzo Villari | last post by:
I've tried to transform this into a not recursive version but without luck... #include <stdio.h> void countdown(int p) { int x;
10
by: MakeMineScotch | last post by:
What's the secret to writing recursive functions that won't crash the computer?
13
by: Mumia W. | last post by:
Hello all. I have a C++ program that can count the YOYOs that are in a grid of Y's and O's. For example, this Y O Y O O Y O Y O Y O O Y O Y Y O Y O Y O O Y O O Y Y O Y O
30
by: Jeff Bigham | last post by:
So, it appears that Javascript has a recursion limit of about 1000 levels on FF, maybe less/more on other browsers. Should such deep recursion then generally be avoided in Javascript?...
35
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.