項(xiàng)目里有圖表展示數(shù)據(jù)的需求操骡,比如[239,213,122,12,321]計(jì)算每個(gè)數(shù)字占總和的百分比,直接四舍五入可能總和不能正好100%
Flutter實(shí)現(xiàn):
print('-----最大余額法-----${maximumBalance([239,213,122,12,321])}');
-----最大余額法-----[26.35%, 23.49%, 13.45%, 1.32%, 35.39%]
import 'package:collection/collection.dart';
/// 最大余額法
List<String> maximumBalance(List<double> data) {
// 總額
double sum = 0;
for (double element in data) {
sum += element;
}
if (sum == 0) {
return [];
}
// 總份額钻弄,共4位數(shù)
double total = 10000;
// 分配份額
List<double> shareList = data.map((e) => e / sum * total).toList();
// 整數(shù)部分
List<int> integerList = shareList.map((e) => e.toInt()).toList();
// 計(jì)算整數(shù)部分的總和
int shareSum = integerList.reduce((value, element) => value + element);
// 小數(shù)部分
List<double> decimalsList = shareList.mapIndexed((index, element) => element - integerList[index]).toList();
// 整數(shù)部分總和小于總份額時(shí)
while (shareSum < total) {
double max = decimalsList[0];
int maxIndex = 0;
// 找出小數(shù)位最大的下標(biāo)
for (int i = 1; i < decimalsList.length; i++) {
if (decimalsList[i] > max) {
max = decimalsList[i];
maxIndex = i;
}
}
// 小數(shù)位最大的加1
integerList[maxIndex] += 1;
// 加1后小數(shù)清零,不參與下次比較
decimalsList[maxIndex] = 0;
// 總數(shù)也需要加1
shareSum += 1;
}
// 圖表數(shù)據(jù)
List<double> dataList = [];
List<String> legendList = [];
for (int element in integerList) {
double data = element / 100;
dataList.add(data);
legendList.add('${data.toStringAsFixed(2)}%');
}
return legendList;
}