mardi 24 janvier 2017

Break Iteration of Java loop with control flow with a recursive method

My attempt at recursion by trying to solve the monkey/coconut/sailor problem.

Im having issues with my for loop stopping. It just iterates though and im unsure where I went wrong.

in my 3 test cases the method testCoconuts returns the values I would like, however my loop will iterate until the last number, even if the true values are sent through the loop.

im sure its my booleans, but i havent been able to figure out what im doing wrong.

public class Test {

    public static boolean testCoconuts(int s, int sr, int c){

        if (c % s == 1 && sr > 0){
            Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
                                  }

        else if (c % s != 1){
            return false;
        }

        else if (sr == 0){
        System.out.println("solved");
        return true;    //returns true in all 3 test cases below
        }

        return false;
    }


   public static void main(String[] args){
       //int s and sr must me entered into the test program 
       //as the same number, ex s= 2, sr = 2

         int sailors = 3;


     Test.testCoconuts(2, 2, 7);  //will print solved
     Test.testCoconuts(3, 3, 79);  //will print solved
     Test.testCoconuts(4,4,1021);  //will print solved



    for (int testNuts = 1; testNuts < 100; testNuts++){
        if (Test.testCoconuts(sailors, sailors, testNuts)==true){
            System.out.println("solved!");
            break;
        }
        else{
            System.out.println(testNuts);
            System.out.println("next iteration");
            System.out.println(testNuts);
        }
}
}
   }

Aucun commentaire:

Enregistrer un commentaire