java - Trouble with splitting an array into chunks -
i have array:
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
i'm trying split two-dimensional array x amount of chunks, of chunks have equal length (in case, 2), assign each value of original array corresponding index within array. increment index of chunk number , reset index iterating through individual arrays hit length of one.
problem is, code wrote perform isn't outputting anything:
public class debug { private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4}; private static void chunkarray(int chunksize) { int chunknumindex = 0; int chunkindex = 0; int numofchunks = (int)math.ceil((double)array.length / chunksize); int[][] twodimensionalarray = new int[numofchunks][chunksize]; (int = 0; < array.length; i++) { twodimensionalarray[chunknumindex][chunkindex] = array[i]; chunkindex++; while(chunknumindex < numofchunks) { if (chunkindex == chunksize) { chunknumindex++; chunkindex = 0; } } } for(int = 0; < chunknumindex; i++) { for(int j = 0; j < chunkindex; j++) { system.out.printf("%5d ", twodimensionalarray[i][j]); } system.out.println(); } } public static void main(string args[]) { chunkarray(2); } }
could of assistance in debugging program?
the problem have unnecessary while(chunknumindex < numofchunks)
makes no sense. if statement sufficient iterate variables correctly:
(int = 0; < array.length; i++) { twodimensionalarray[chunknumindex][chunkindex] = array[i]; chunkindex++; if (chunkindex == chunksize) { chunknumindex++; chunkindex = 0; } }
also, remember values of chunknumindex
, chunkindex
dynamic, last loops, use twodimensionalarray.length
, twodimensionalarray[0].length
instead:
for(int = 0; < twodimensionalarray.length; i++) { for(int j = 0; j < twodimensionalarray[0].length; j++) { system.out.printf("%5d ", twodimensionalarray[i][j]); } }
Comments
Post a Comment