- A+

Category：Languages

How do I split a number into equal parts or as close to equal as possible. See example below:

If I have a value of 61 that i want to distribute between two groups, it would be 30.5 and 30.5. Doubles (decimals) are no good, so in this regard the closest split is 30 and 31.

Similarly 42 / 5 = 8.4, however I need the system to return (8, 8, 8, 9, 9) which is the closest split with whole numbers.

Solved it guys:

` if(sum % numberOfTeams != 0) { al.add(0, sNOT); for(int i = 0; i < numberOfTeams - 1; i++) { int remover = sum - sNOT; if(remover % (sNOT + 1) == 0) { al.add(i+1, sNOT + 1); }else { al.add(i + 1, sNOT); } } } `

}

Here is a solution which entirely uses `Arrays`

, a little shorter with no loops. Validity check should also be applied as suggested above

` int value = 42; int groups = 5; int residue = value % groups; int[] res = new int[groups]; int division = value / groups; Arrays.fill(res, 0, residue, division +1); Arrays.fill(res, residue, res.length, division); System.out.println(Arrays.toString(res)); `