Home > Mobile >  How calculate array integers sum array with index belongs to an interval in Java?
How calculate array integers sum array with index belongs to an interval in Java?

Time:04-24

I'm trying to calculate the sum of the integers of array whose index belongs to the interval [n1; n2]

n1 & n2 are int & 0 <= n1 <= n2 < array.length

int[] array = new int[] {0, 1, 2, 3, 4, 5, 3}; 
int zeroToOne = calc(array,0, 1); // Should return 1
int zeroToFive = calc(array,0, 5); // Should return 15
int doubleZero = calc(array,0, 0); // Should return 0
int zeroToSix = calc(array, 0,6); // Should return 18

So I've tried three methods

First method:

public static int calc(int[] array, int n1, int n2) {

    int sum = 0;
    for (int i = 0; i < array.length; i  ){
        if (i <= n2 && n1 <= i) {
            sum  = i;
        }
    }
    return sum;
}

}

I got:

1 15 0 21

Second method:

public static int calc(int[] array, int n1, int n2) {

    int sum = 0;
    for (int a: array){
        if (n1 <= a && a <= n2){
            sum  = a;
        }
    }
    return sum;
}

I got:

1 18 0 18

Third method:

public static int calc(int[] array, int n1, int n2) {
      
    return Arrays.stream(array, n1, n2).sum();
}

And I got:

0 10 0 15

How can I solve this problem?

CodePudding user response:

A small change to your first function and it should work:

  public static int calc(int[] array, int n1, int n2) {

    int sum = 0;
    for (int i = n1; i <= n2; i  ) {
      sum  = array[i];
    }
    return sum;
  }

Note that we iterate over the elements from position n1 to n2, and summing them up.

CodePudding user response:

Use your first method but index the array.

public static int calc(int[] array, int n1, int n2) {

    int sum = 0;
    for (int i = 0; i < array.length; i  ){
        if (i <= n2 && n1 <= i) {
            sum  = array[i]; // <-- change i to array[i]
        }
    }
    return sum;
}

Using your test also ensures that n1 and n2 are within the array which is a good idea on your part.

CodePudding user response:

The method you call:

Arrays.stream(array, n1, n2)

has the following definition in documentation:

stream(int[] array, int startInclusive, int endExclusive)

so you can see that the 3rd parameter is exclusive.

What you can do is just call it with the last index 1. This should be fine:

return Arrays.stream(array, n1, n2 1).sum();
  • Related