Swapping contents of an array of unequal columns -
i have question , far able create method sum values of integers in row , compare sum of other row, don't know how swap rows. help?
the question is:
write java program given two-dimensional array, reorders rows such row highest row sum first row.
if program called following array:
1 3 5 9 2 100 2 2 3
then output should be:
2 100 1 3 5 9 2 2 3
the following steps should performed:
- calculate row sum
- find index of row maximum sum
- swap row of maximum sum row 0
public static void main(string[] args) { int [][] = {{1,3,5,9},{2,100},{2,2,3}}; int max = sum(0,a); int index = 0; (int = 1; < a.length; i++) { if( max < sum(i,a) ) { max = sum (i,a); index = i; } } } public static int sum(int y, int[][]x) { int sum = 0; for(int j = 0; j<x[y].length; j++) sum+= x[y][j]; return sum; }
excuse insolence, have never written in java , cann't try - haven't tool, think, code should this
public static void main(string[] args) { int [][] = {{1,3,5,9},{2,100},{2,2,3}}; int max = sum(a[0]); int index = 0; (int = 1; < a.length; i++) { int t = sum(a[i]); if( max < t ) { max = t; index = i; } } if (index != 0) { int tmp[] = a[0]; a[0] = a[index]; a[index] = tmp; } } public static int sum(int[]x) { int sum = 0; for(int j = 0; j<x.length; j++) sum+= x[j]; return sum; }
Comments
Post a Comment