'An array of `int` values ​and return an array of boolean values

The task The correct implementation should receive an array of int values and return an array of booleans where each element is a result of a check if a corresponding element is a sum of two previous elements in given array.

Details:

The length of given array is guaranteed to be 2 or more. Given array is guaranteed to be not null. Method returns an array of booleans where each element is a result for corresponding element in given array. First two elements of the boolean array are always false. Example Input array: [1, -1, 0, 4, 6, 10, 15, 25]

Output array: [false, false, true, false, false, true, false, true] What's wrong in my code? I have a result [false, false, false, false, false, false, false, false]

enter code here

public class SumOfPrevious {

public static void main(String[] args) {
    int[] array = new int[]{1, -1, 0, 4, 6, 10, 15, 25};

    System.out.println(Arrays.toString(getSumCheckArray(array)));
}

public static boolean[] getSumCheckArray(int[] array) {
    boolean[] booleans = new boolean[array.length];
    for (int i = 0; i < array.length - 1; i++) {
        for (int sum : array) {
            sum = array[i] + array[i + 1];
            if (sum == array[i]) {
                Arrays.fill(array, sum);
            }
        }
    }

    return booleans;
}

}



Solution 1:[1]

Why do you try to fill up the initial array with "sum" value like this?

Arrays.fill(array, sum);

That's incorrect and does not transform, the only array that needs to be transformed, meaning "booleans" array.

Besides that, there's no need to have additional for loop:

 for (int sum : array) {
  sum = array[i] + array[i + 1];
 }

You can check the value of the sum with each iteration of the main for loop:

import java.util.Arrays;

public class Main
{

  public static void main (String[]args)
  {
    int[] array = new int[]{ 1, -1, 0, 4, 6, 10, 15, 25 };

      System.out.println (Arrays.toString (getSumCheckArray (array)));
  }

  public static boolean[] getSumCheckArray(int[] array) {
    boolean[] booleans = new boolean[array.length];
    int sum = 0;

    for (int i = 0; i < array.length - 2; i++) {
      sum = array[i] + array[i + 1];
      if (sum == array[i + 2]) {
        booleans[i + 2] = true;
      }
    }
    return booleans;
  }
}

Note that this way, for loop ends up on the the element which is 2 positions before the last one:

for (int i = 0; i < array.length - 2; i++) 

But the condition:

if (sum == array[i+2]) {
   booleans[i+2] = true;
}

still will be checked for the last element array[i+2].

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JacobTheKnitter