简体   繁体   中英

checking an array of ints to see if the sum of any two elements equals another

Before anyone says it...yes...this is a homework assignment. Basically, I am going to be given an array of ints and I am suppose to write a program that accepts the array and then checks it to see if any two elements sum up to equal a third one.

So if the array is [1 2 3 4] then it's a "yes" because 1+2=3 and 1+3=4 but if it's [1 1 1 1] then it's a "no".

I've already written all other methods, I just need the logic to do what I explained above, preferably using recursion (because that's the assignment).

I honestly don't even know where to start with recursion, never used it before.

You could use this, to find the sum of every two numbers in the array, and then compare them with the array's contents.

 for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            int sum = array[i] + array[j];
            for(int k = 0; k < array.length; k++) {
                if(array[k] == sum)
                    return true;
                else
                    return false;
            }
        }
    }

This may not be the most efficient, but it works, and that is what you were looking for.

Here I have used Integer[]

Integer[] arr = new Integer[] { 1, 2, 3, 4 };
for (int i = 0; i < arr.length - 1; i++) {
    if(arr[i] == 0) {
         continue;
    }
    for (int k = i + 1; k < arr.length; k++) {
        if (arr[k] != 0
                && Arrays.asList(arr).contains(arr[i] + arr[k])) {
            return true;
        }
    }
}
return false;

Arrays.asList(arr) converts arr to a list and contains(arr[i] + arr[k]) will check whether the sum of the 2 elements are present in arr

You could always use a for loop like this:

for(int i = 0; i+2 < array.length; i++) //i + 2 because the last two element pair won't be used
        if(array[i+2] == array[i] + array[i+1]){return true;} //Or whatever else you want to return
        else{return false;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM