mardi 29 août 2017

Sum Experiment array / loop dilemma

I am writing a program and I can't seem to make the IF action loop and check all of the arrays in the main. My job is to figure out whether there exists any pair of numbers (i.e., any two elements) in this ascending sorted array that will add up to 20. All you need to do is to sum the values these two pointers point to and see if they are equal to 20, if so, output. otherwise, inspect the sum, if the sum is greater than 20,decrement the second pointer and if the sum is less than 20, increment the first pointer. cannot use the nested for loop approach!! Not sure how to fix this... i've been at it for hours and have handwritten it with no luck. thank you!!

// if val of arr at index i is smaller than at arr j, then return
    // smaller value
    // This function will inspect the input to find any pair of values that
    // add up to 20
    // if it find such a pair, it will return the *index* of the smallest
    // value
    // if it does not find such as pair, it will return -1; 

public class SumExperiment {

public static int check_sum(int[] array) {
int i = array[0];
int y = array.indexOf(array.length); // need value @ index of array.length to begin

//loop to repeat action

for (int arraysChecked = 0; arraysChecked < 5; arraysChecked++ )
{
    if ( i + y == 20)
        {
        return i;
    //  System.out.print(array[i]);
        }
            else if ( i + y > 20)
                {
                y--; //index @y
                }
            else if (i + y < 20)
                {
                i++; //index @x
                }

    if ( i + y != 20)
    {
        return -1;
    }
    arraysChecked++;
}
return -1;  //because must return int, but this isn't correct
}


public static void main(String[] args) {
    int[] array1 = new int[] { 5, 7, 8, 9, 10, 15, 16 };
    if (check_sum(array1) != 0)
        System.err.println("TEST1 FAILED");

    int[] array2 = new int[] { 3, 5, 8, 9, 10, 15, 16 };
    if (check_sum(array2) != 1)
        System.err.println("TEST2 FAILED");

    int[] array3 = new int[] { 3, 4, 6, 9, 10, 14, 15 };
    if (check_sum(array3) != 2)
        System.err.println("TEST3 FAILED");

    int[] array4 = new int[] { 6, 7, 8, 9, 10, 15, 16 };
    if (check_sum(array4) != -1)
        System.err.println("TEST4 FAILED");

    System.out.println("Done!!!");
}
}

Aucun commentaire:

Enregistrer un commentaire