As shown in the above picture, sometimes we find that the total value in a pie chart is not equal to 100%. By using largest remainder method, we can address this problem.
In largest remainder method, each element is first allocated a percentage value equal to their integer. The elements are then ranked on the basis of the fractional remainders, and the elements with the largest remainders are each allocated one additional percentage until all the percentages have been allocated.
For example, we have an array {3, 4, 5}, and the sum of the array elements is 12.
3/12 * 100 = 25, and the remainder is 0. 4/12 * 100 = 33.33, and the remainder is 0.33. 5/12 * 100 = 41.67, and the remainder is 0.67.
According to the integer part, we first allocate a percentage value of 25 to 3, a percentage value of 33 to 4, and a percentage value of 41 to 5. Now we have allocated 25+33+41=99 percentage. For the last 1 percent, we allocate it to 5 because its remainder is larger than 3 and 4. Therefore we have [25, 33, 42] for value 3, 4 and 5.
// Get the percentage value of all the elements in an array, // which is based on the largest remainder method. publicstaticint[] getPercentageValue(int[] array) { if (array.length == 0) { thrownew IllegalArgumentException(); }
int sum = getSum(array); if (sum == 0) { System.out.println("Cannot compute percentage value of the array."); }
int[] result = newint[array.length];
// Each element is first allocated a percentage value equal // to their integer. for (int i = 0; i < array.length; i++) { result[i] = array[i] * 100 / sum; }
int currentSumOfPercentage = 0; for (int i : result) { currentSumOfPercentage += i; }
double[] remainder = newdouble[array.length]; for (int i = 0; i < result.length; i++) { remainder[i] = (double) array[i] / sum * 100 - result[i]; }
// The elements are then ranked on the basis of the fractional remainders, // and the elements with the largest remainders are each allocated one // additional percentage until all the percentages have been allocated. while (currentSumOfPercentage < 100) { int index = getMax(remainder); result[index]++; remainder[index] = 0; currentSumOfPercentage++; }
return result;
}
// Get the sum of all the elements in an array. publicstaticintgetSum(int[] array){ int sum = 0; for (int i : array) { sum += i; } return sum; }
// Get the index of the maximal element in an array. publicstaticintgetMax(double[] array){ int maxIndex = 0; double maxValue = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > maxValue) { maxValue = array[i]; maxIndex = i; } }
return maxIndex; }
// main method to test the result publicstaticvoidmain(String[] args){ int[] array = {3, 3, 4}; int[] result = getPercentageValue(array); System.out.println(Arrays.toString(result));// output: [30, 30, 40]