Home > Enterprise >  Is there a way to use : to add a range of values in an array?
Is there a way to use : to add a range of values in an array?

Time:11-27

I have an array and I am trying to sum the values of just a portion of the array.

For example my array is [1,2,3,4,5,6], but I want to add the values only to the third element

[1,2,3]. I thought I used a method involving the semi colon before, but I cant remember for sure.

something like int sum = Sum (arr[0]:arr[2]) but I am not sure. Does something like this exist?

I think I used it in Python a few years ago.

CodePudding user response:

There is no built in method to sum up a sub array. The simplest way could be to stream over the sub array:

int[] myArray = {1,2,3,4,5,6};

int sum = Arrays.stream(myArray, 0, 3).sum();

where 0 and 3 are the start and end indices (Start inclusiv, end exclusiv)

CodePudding user response:

Extending Eritrean's excellent answer you can create an interface with a meaningful name and tuck it away in your library.

interface IntRangeSum {
    static public int apply(int[] a, int start, int end) {
         return Arrays.stream(a, start, end).sum();
    }
}


int[] a = {1,2,3,4,5};
int result = IntRangeSum.apply(a, 2, 4);
System.out.println(result);

prints

7    

CodePudding user response:

You're looking for the slicing notation [start:stop:step]

values = [1,2,3,4,5,6]
s = sum(values[:3])

CodePudding user response:

import java.util.*;
public class MyClass {
    public static void main(String args[]) {
      int[] oldArray ={1,2,3,4,5};
      int[] newArray = Arrays.copyOfRange(oldArray, 0, 3);
      int sum = 0;
      for (int i: newArray) {
        sum  = i;
      }
      System.out.println("Sum = "   sum);
    }
}

Output: 6

As far as I know Java doesn't have the slicing notation you know from Python, but this, while more verbose, should do the trick.

CodePudding user response:

You could use the appropriate variant of java.util.Arrays.copyOfRange methods to create and operate on a slice.

Or use a loop:

int sum = 0;
for(var i=0; i < 3; i  ) {
  sum = sum   i
}

CodePudding user response:

Another option would be to use combination Arrays.stream() IntStream.limit():

int[] arr = // initializing the array

int sum = Arrays.stream(arr).limit(3).sum();
  • Related