Results 1 to 6 of 6
- 07-16-2010, 02:41 PM #1
Member
- Join Date
- Jul 2010
- Posts
- 3
- Rep Power
- 0
Help needed to turn a recursive method into iterative
Hi there! I'm in need of a bit of help, I'm going crazy with some Java practice I have to do.
I need to turn this recursive method (cal):
public class Recursivo {
private int valores[] = {12, 13, 25, 34, 56, 75, 16, 78, 11, 65, 89};
public int cal (int a, int b)
{
int i = (a+b)/2;
if (a<=b) {
return (valores[i]%2) + cal(a, i-1) + cal(i+1, b);
}
else {
return 0;
}
}
}
into a non recursive (iterative) method that does the same thing.
Anyone can spare some time to help me out?
Thanks!
- 07-16-2010, 03:27 PM #2
Do you have a description of what the app does?
- 07-16-2010, 04:05 PM #3
Member
- Join Date
- Jul 2010
- Posts
- 3
- Rep Power
- 0
Nope, sorry. I was given that code as it is and asked to change it so it does the same thing without using recursivity :(
- 07-16-2010, 04:07 PM #4
A description of what it does could help you find another way to code it.
- 07-16-2010, 06:01 PM #5
Member
- Join Date
- Jul 2010
- Posts
- 3
- Rep Power
- 0
Believe me or not, you just made me solve the problem :D
I tried to understand the purpose of that method for the n-th time and finally found the reasoning behind it (it returns how many odd numbers are stored in the array between 2 given positions (the method params a & b)).
So...
public int cal2 (int a, int b)
{
int total = 0;
if (a<=b){
for (int i=a;i<=b;i++){
total+= valores[i]%2;
}
return total;
}
else
return 0;
}
Thanks a lot! :D
- 07-16-2010, 06:13 PM #6
Similar Threads
-
Creating a 'turn' method
By StateofMind in forum New To JavaReplies: 6Last Post: 11-27-2012, 10:36 AM -
Turning Recursion Method into Iterative method
By mattakuevan in forum New To JavaReplies: 9Last Post: 06-15-2010, 06:46 AM -
Java class HashIt with a static recursive method and a static iterative method
By kezkez in forum New To JavaReplies: 3Last Post: 02-09-2010, 05:22 AM -
Recursive method using int array, help needed
By chupalo17 in forum New To JavaReplies: 4Last Post: 09-07-2009, 11:15 PM -
Recursive Method
By bluegreen7hi in forum New To JavaReplies: 5Last Post: 11-29-2007, 04:45 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks