i have m×n matrix , need change number of columns (increase or decrease). have following code not work.
public class resize { public static int [][] = new int [2][2]; public static int i, j; public static void main(string[] args) { = (int[][])resizearray(a,4); for(i = 0 ; < 2 ; i++){ for(j = 0 ; j < 4 ; j++){ a[i][j] = j+i; system.out.print(a[i][j]+" "); } system.out.println(""); } } // resize arr dimension n = 20 dimension n = 14 /////////////// private static object resizearray (object oldarray, int newsize) { int oldsize = java.lang.reflect.array.getlength(oldarray); class elementtype = oldarray.getclass().getcomponenttype(); object newarray = java.lang.reflect.array.newinstance(elementtype, newsize); int preservelength = math.min(oldsize, newsize); if (preservelength > 0) system.arraycopy(oldarray, 0, newarray, 0, preservelength); return newarray; } }
the problem you're changing number of rows rather number of columns in resizearray
method. can tell printing @ end of main method, a.length
, equals number of rows in 2d array. line
int oldsize = java.lang.reflect.array.getlength(oldarray);
is same setting oldsize
a.length
. both agree oldsize
number of rows in inputted array. , line
system.arraycopy(oldarray, 0, newarray, 0, preservelength);
copies elements oldarray[0]
, oldarray[1]
, oldarray[2]
, ... oldarray[preservelength - 1]
newarray[0]
, newarray[1]
, newarray[2]
, ... newarray[preservelength - 1]
respectively. 2d array, you're copying rows of old array , putting them new array.
a possible solution make new array of size math.min(oldarray[0].length, newlength)
, loop through new array putting elements old array new array.
private static int[][] resizearray (int[][] oldarray, int newsize) { int oldsize = oldarray[0].length; //number of columns int preservelength = math.min(oldsize, newsize); int[][] newarray = new int[oldarray.length][newsize]; for(int = 0; < oldarray.length; i++) { for(int j = 0; j < preservelength; j++) { newarray[i][j] = oldarray[i][j]; } } return newarray; }
Comments
Post a Comment