M.S*_*hiz 5 java algorithm math double numbers
如何将数字分成相等的部分或尽可能接近相等.见下面的例子:
如果我想要在两组之间分配值61,那么它将是30.5和30.5.双打(小数)不好,所以在这方面最接近的分数是30和31.
类似地,42/5 = 8.4,但是我需要系统返回(8,8,8,9,9),这是与整数最接近的分裂.
解决了它们:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
这是一种解决方案:
public static int[] closestSplit(int intToSplit, int noOfGroups) {
int[] result = new int[noOfGroups];
Arrays.fill(result, intToSplit / noOfGroups);
for (int i = 0; i < intToSplit % noOfGroups; i++) {
result[i]++;
}
return result;
}
// usage:
System.out.println(Arrays.toString(closestSplit(42, 5)));
Run Code Online (Sandbox Code Playgroud)
基本上,它首先创建一个长度数组,然后用和noOfGroups
的整数除法填充该数组。接下来,它向数组的第一个元素添加 1 。intToSplit
noOfGroups
intToSplit mod noOfGroups
如果需要将结果按升序排序,可以从数组末尾开始循环或使用Arrays.sort
.