There is a task in which you need to remove rows from a multidimensional array so that the sum of the digits left in the array approximates as a percentage of the total amount of the array to the dial set by the user in the console. What kind of algorithm did it throw ... But I can't understand why my cycle is endless? And secondly, how can I delete a line? (Convert a line to a sheet and delete? Or the entire array? (I just started to learn, so do not scold)), otherwise I just change the line that I would like to delete.

public class Task15 { public static void main(String[] args) { // Matrix percent Scanner percent = new Scanner(System.in); int percentNedded = percent.nextInt(); int percentLeft = 100; int[][] matrixRandom = Util.createRandomMatrix(10, 10, 100); for (int i = 0; i < matrixRandom.length; ++i) { System.out.println(Arrays.toString(matrixRandom[i])); } int indexOfMax = Util.rowIndexOfMaxNumber(matrixRandom);// index of max number int matrixSum = Util.matrixSumm(matrixRandom); System.out.println(matrixSum + " " + percentNedded); int row1 = 0; int row2 = matrixRandom.length - 1; while (true) { int pecentDifferent = percentLeft - percentNedded; int row1summ = Util.matrixRowSumm(matrixRandom, row1);// тут сумма строки int row2summ = Util.matrixRowSumm(matrixRandom, row2); if (row1summ > row2summ && (row1summ < pecentDifferent * matrixSum / 100) && row1 != indexOfMax) { for (int i = 0; i < matrixRandom[row1].length; i++) { matrixRandom[row1][i] = 0; } percentLeft -= row1summ / matrixSum * 100; row1++; } else { if (row2summ < pecentDifferent * matrixSum / 100 && row2 != indexOfMax) { for (int i = 0; i < matrixRandom[row2].length; i++) { matrixRandom[row2][i] = 0; } percentLeft -= row2summ / matrixSum * 100; row2--; } else break; } } for (int i = 0; i < matrixRandom.length; ++i) { System.out.println(Arrays.toString(matrixRandom[i])); } } 

}

  • Most likely percentLeft - = row1summ / matrixSum * 100 == percentLeft well, say row1summ = 100 turns out 100 / matrixSum * 100 = 1 / matrixSum = 0.1, say. ideone.com/JsF87w here look at the result. Interestingly it turns out - Senior Pomidor
  • it is necessary to round up2 rowum / matrixSum * 100 - Senior Pomidor
  • there even you get 100- (10/100) * 100 = 100-10 = 100 ... that is, I don't need to declare an int, but a different type of variable? - Oleksandr
  • BigInteger must be rounded up - Senior Pomidor

1 answer 1

Probably

 percentLeft -= row1summ / matrixSum * 100 == percentLeft 

Let's say row1summ = 100 , it turns out 100/matrixSum * 100 = 1/matrixSum = 0,1 . Look here for the result . Interesting turns out

 100- 1/10 = 100 

For int you need row2summ / matrixSum * 100 round up.