Page 1 of 1

recursive method to test if we can get a number n from an array []a

Posted: Tue Mar 06, 2018 4:44 am
by maty.tsoraro@gmail.com
hi
please help identify why the program is not running

this is the URL link :
http://www.beta.browxy.com#USER_159638

and this is the code :

Code: Select all

public class Test2012{
public static void main(String[]args){
    int[]a = {4,5};
    if(!Exam2012.isSumOf(a,13))
    System.out.println("No solution");   
    }
public class Exam2012{
    public static boolean isSumOf(int[]a,int n)//array a of numbers  and a number n
    {
        int[]history = new int[n];
        return isSumOf(a,n,0,history,0)
    }
    
    private static boolean isSumOf(int[]a,int n , int i ,int[]history,int ind)
    // i tells us were we are,
    //history saves the number we tried till we got  a certain result
    //ind telss us were we are in the history
    {
        if(n == 0)
        {
            printArray(history ,0,ind);
            return true;
        }
        if(n < 0  || i == a.length)
        return flase;
        history[ind] = a[i];
        if(isSumOf(a,n-a[i],i,history,ind+1))
        return true;
        return isSumOf(a,n,i+1,history,ind);
    }
    private static void printArray(int[]a,int i ,int to)
    {
        if(i<to){
            System.out.print(a[i] + "\t" );
            printArray(a,i+1,to);
        }
    }
    
}
}

Re: recursive method to test if we can get a number n from an array []a

Posted: Wed Mar 07, 2018 4:11 am
by dbremmen@gmail.com
Hi!

You had many problems in your code:
I fixed them here -> http://www.beta.browxy.com#ALIEN_11558

Here is the code pasted

Code: Select all

public class Test2012 {
    
public static void main(String[]args) {
    int[]a = {4,5};
    if(!Exam2012.isSumOf(a,13))
    System.out.println("No solution");   
}

}

class Exam2012 {
    public static boolean isSumOf(int[]a,int n)//array a of numbers  and a number n
    {
        int[]history = new int[n];
        return isSumOf(a,n,0,history,0);
    }
    
    private static boolean isSumOf(int[]a,int n , int i ,int[]history,int ind)
    // i tells us were we are,
    //history saves the number we tried till we got  a certain result
    //ind telss us were we are in the history
    {
        if(n == 0)
        {
            printArray(history ,0,ind);
            return true;
        }
        if(n < 0  || i == a.length)
        return false;
        history[ind] = a[i];
        if(isSumOf(a,n-a[i],i,history,ind+1))
        return true;
        return isSumOf(a,n,i+1,history,ind);
    }
    private static void printArray(int[]a,int i ,int to)
    {
        if(i<to){
            System.out.print(a[i] + "\t" );
            printArray(a,i+1,to);
        }
    }
    
}

Re: recursive method to test if we can get a number n from an array []a

Posted: Sat Mar 10, 2018 9:13 pm
by maty.tsoraro@gmail.com
thanks you very much :P