-3

How do I create a subarray of an array in Java. Given a number 3 and x [2,4,6,30,9], the answer is X1[2,4,6] X2[4,6,30] X3[6,30,9]

This is what I have so far, but it only prints the first three elements. I also have to print the median of every subArray.


double[] floatsArr = new double[3]; 

// floats is the array with all the elements in

for(int i = 0; i < floats.length; i++){
            
     for(int k = 1; k < (filterSize+1); k++){
                 floatsArr[k] = floats[k];  
                 System.out.println(floatsArr[k]);

    }
}

Ruli
  • 2,592
  • 12
  • 30
  • 40
  • Use [Arrays.copyOfRange()](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/Arrays.html#copyOfRange(float%5B%5D,int,int)) –  Aug 12 '21 at 21:57

2 Answers2

0

It seems you want to create all subarrays of a given length from an array.

You can do it by hand:

static double[][] subArrays(double[] arr, int k)
{
    double[][] subArrs = new double[arr.length-k+1][k];
    
    for(int i=0; i<subArrs.length; i++)
        for(int j=0; j<k; j++)
            subArrs[i][j] = arr[i+j];
    
    return subArrs;
}

Or use the built-in method Arrays.copyOfRange:

static double[][] subArrays(double[] arr, int k)
{
    double[][] subArrs = new double[arr.length-k+1][];
    
    for(int i=0; i<subArrs.length; i++)
        subArrs[i] = Arrays.copyOfRange(arr, i, i+k);
    
    return subArrs;
}

Test:

double[] arr = {2, 4, 6, 30, 9};
    
for(double[] subArr : subArrays(arr, 3))
    System.out.println(Arrays.toString(subArr));

Output:

[2.0, 4.0, 6.0]
[4.0, 6.0, 30.0]
[6.0, 30.0, 9.0]
RaffleBuffle
  • 5,396
  • 1
  • 9
  • 16
0

Here is a convenient way to do it.

Given a group sub array size and source array

int groupSize = 3;
double[] arr = { 2, 4, 6, 30, 9 };
  • first stream ints from 0 to arr.length - groupSize. This will serve as the starting index to create each subarray.
  • then Stream the actual indices of the source array to create the subarray.
  • and map the double values using the previous index into the stream and then gather into an array.
  • then collect those arrays into a multi-array array.
double[][] result =
        IntStream.rangeClosed(0, arr.length - groupSize)
                .mapToObj(i -> IntStream.range(i, groupSize + i)
                        .mapToDouble(k -> arr[k]).toArray())
                .toArray(double[][]::new);


for (double[] a : result) {
    System.out.println(Arrays.toString(a));
}

Prints

[2.0, 4.0, 6.0]
[4.0, 6.0, 30.0]
[6.0, 30.0, 9.0]

And even shorter is to use Arrays.copyOfRange() in place of the second stream.

double[][] result = IntStream
        .rangeClosed(0, arr.length - groupSize)
        .mapToObj(i -> Arrays.copyOfRange(arr, i, i + groupSize))
        .toArray(double[][]::new);
WJS
  • 36,363
  • 4
  • 24
  • 39