Last active
March 10, 2024 20:16
-
-
Save lesleh/7724554 to your computer and use it in GitHub Desktop.
Java function to split an array into chunks of equal size. The last chunk may be smaller than the rest.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example usage: | |
// | |
// int[] numbers = {1, 2, 3, 4, 5, 6, 7}; | |
// int[][] chunks = chunkArray(numbers, 3); | |
// | |
// chunks now contains [ | |
// [1, 2, 3], | |
// [4, 5, 6], | |
// [7] | |
// ] | |
public static int[][] chunkArray(int[] array, int chunkSize) { | |
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize); | |
int[][] output = new int[numOfChunks][]; | |
for(int i = 0; i < numOfChunks; ++i) { | |
int start = i * chunkSize; | |
int length = Math.min(array.length - start, chunkSize); | |
int[] temp = new int[length]; | |
System.arraycopy(array, start, temp, 0, length); | |
output[i] = temp; | |
} | |
return output; | |
} |
Very helpful. Thanks for this
what is the licence for this?
Is it mit
As long as your array length isn't close to Integer.MAX_VALUE
, using
int numOfChunks = (array.length + chunkSize - 1) / chunkSize;
avoids the integer->double->integer conversion, and removes any worries about rounding error along with it.
How About 2-Dimensional Array?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please add license information.