CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2011

    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

    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);
    						System.out.println("Move " +num+": "+m);
                        // else's to handle other cases of the function

  2. #2
    Join Date
    May 2006

    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?
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

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

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.