需求描述:
给定一个整数数组,例如:[2, 3, 4],计算各个元素的百分比,要求百分比累加为100%。
input = [2, 3, 4]
output = [22.22, 33.33, 44.45]
项目依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
代码实现:
public class PercentUtils {
public static double getPercentValue(int[] arr, int idx, int precision) {
if (idx < 0 || (arr.length - 1) < idx) {
return 0;
}
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
if (sum <= 0) {
return 0;
}
double digits = Math.pow(10, precision);
double[] votesPerQuota = new double[arr.length];
for (int i = 0; i < arr.length; i++) {
double val = arr[i] / sum * digits * 100;
votesPerQuota[i] = val;
}
double targetSeats = digits * 100;
double[] seats = new double[arr.length];
for (int i = 0; i < votesPerQuota.length; i++) {
seats[i] = Math.floor(votesPerQuota[i]);
}
double currentSum = 0;
for (int i = 0; i < seats.length; i++) {
currentSum += seats[i];
}
double[] remainder = new double[arr.length];
for (int i = 0; i < seats.length; i++) {
remainder[i] = votesPerQuota[i] - seats[i];
}
while (currentSum < targetSeats) {
double max = Double.MIN_VALUE;
int maxId = 0;
for (int i = 0; i < remainder.length; ++i) {
if (remainder[i] > max) {
max = remainder[i];
maxId = i;
}
}
++seats[maxId];
remainder[maxId] = 0;
++currentSum;
}
return seats[idx] / digits;
}
}
运行效果:
@SpringBootTest
public class TestPercentUtils {
@Test
public void testGetPercentValue01() {
int[] arr = new int[]{2, 3, 4};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i] + " percent = " + PercentUtils.getPercentValue(arr, i, 2));
}
}
@Test
public void testGetPercentValue02() {
int[] arr = new int[]{2, 2, 2};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i] + " percent = " + PercentUtils.getPercentValue(arr, i, 2));
}
}
}
2 percent = 22.22
3 percent = 33.33
4 percent = 44.45
2 percent = 33.34
2 percent = 33.33
2 percent = 33.33
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)