Here you can find the source of divideArray(T[] arr, Integer... cuts)
cuts
.Parameter | Description |
---|---|
T | Type of array elements |
arr | The array to divide |
cuts | Cut positions for divide operations |
arr
according to the given cut positions
public static <T> List<T[]> divideArray(T[] arr, Integer... cuts)
//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; } }