-
October 14th, 2011, 05:30 PM
#1
Recursive function problem
Hi all, i am writing a function, below, that is part of a program that finds all possible solutions to a game. There is an array "moves" that contains strings (i.e. "1, 2,4","3,6,9"..etc) all being possible that can be made in the game. the Move function simply runs these values and returns a string of a plausible move while also decrementing "pegsLeft" so the function will eventually end when pegs becomes greater than pegsToRemain -- the number of pegs allowed to remain obviously--
This all works well until the for-loop becomes false. 'i' does not seem to reinitialize itself to 0 when the function gets recalled. This causes an overflowerror the second time the function is called because i is set to moves.length when it starts.
ive tried a few different things such as referring to another variable and other for loops, while loops, if statements and none of them seem to work. its probbaly something silly but i've been staring for too long. any help would be appreciated. thanks
Code:
public void moves(int pegs){
String m="";
if(pegs >=pegsToRemain){//potentially the base case
for(int i = 0;i<moves.length;i++){
holder = moves[i].split(",");
from = Integer.parseInt(holder[0]);
over = Integer.parseInt(holder[1]);
to = Integer.parseInt(holder[2]);
m = Move(from, over, to);
if(m!=""){
num++;
System.out.println("Move " +num+": "+m);
}
}
moves(pegsLeft);
}
else{
// else's to handle other cases of the function
}
-
October 15th, 2011, 06:53 AM
#2
Re: Recursive function problem
'i' does not seem to reinitialize itself to 0 when the function gets recalled.
What makes you think that, are you suggesting Java's for loop is broken? Have you added print statements to find out what i's value is and what the flow of execution is?
What sets/changes the contents of the move, pegsLeft and pegsToRemain variables?
BTW why are you encoding int values into a string and then decoding them in the method - why not put them in an instance of a class designed to hold the int 3 values?
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|