Java Array Divide divideArray(T[] arr, Integer... cuts)

Here you can find the source of divideArray(T[] arr, Integer... cuts)

Description

Divides the given array using the boundaries in cuts.
Cuts are interpreted in an inclusive way, which means that a single cut at position i divides the given array in 0...i-1 + i...n
This method deals with both cut positions including and excluding start and end-indexes

License

Open Source License

Parameter

Parameter Description
T Type of array elements
arr The array to divide
cuts Cut positions for divide operations

Return

A list of subarrays of arr according to the given cut positions

Declaration

public static <T> List<T[]> divideArray(T[] arr, Integer... cuts) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.Arrays;

import java.util.List;

public class Main {
    /**//from   ww w. java 2 s .  c  om
     * Divides the given array using the boundaries in <code>cuts</code>.<br>
     * Cuts are interpreted in an inclusive way, which means that a single cut
     * at position i divides the given array in 0...i-1 + i...n<br>
     * This method deals with both cut positions including and excluding start
     * and end-indexes<br>
     * 
     * @param <T>
     *            Type of array elements
     * @param arr
     *            The array to divide
     * @param cuts
     *            Cut positions for divide operations
     * @return A list of subarrays of <code>arr</code> according to the given
     *         cut positions
     */
    public static <T> List<T[]> divideArray(T[] arr, Integer... cuts) {
        Arrays.sort(cuts);
        int c = cuts.length;
        if (cuts[0] < 0 || cuts[c - 1] > arr.length - 1)
            throw new IllegalArgumentException("cut position out of bounds.");
        int startIndex = cuts[0] == 0 ? 1 : 0;
        if (cuts[c - 1] != arr.length - 1) {
            cuts = Arrays.copyOf(cuts, cuts.length + 1);
            cuts[cuts.length - 1] = arr.length - 1;
            c++;
        }
        List<T[]> result = new ArrayList<>(c - startIndex);
        int lastEnd = 0;
        for (int i = startIndex; i <= c - 1; i++) {
            int c2 = i < c - 1 ? 0 : 1;
            result.add(Arrays.copyOfRange(arr, lastEnd, cuts[i] + c2));
            lastEnd = cuts[i];
        }
        return result;
    }
}

Related

  1. divide(int[] array1, int[] array2)
  2. divide(long[] array, double value)
  3. divideAbsolute(double[] one, double[] two)
  4. divideAndConquer(int[] array, int num)
  5. divideArray(float[] array, float num)
  6. divideArrayElements(final int[] array, final int divisor)
  7. divideBytearrays(byte[] ret, int headerLength, byte[] bArr)
  8. divideByteArrayToChunks(byte data[], int chunkSize)
  9. divideElements(double[] v1, double[] v2, double[] rs)