大约3天后,我试图找出一个通用的公式来在人们之间分配付款。到目前为止,在Java中,我会执行以下操作:
NameArray [Me, Dad, Mum, Sister]
singlePayment[10,5,15,20,2,4]
totalPaymentperPerson[25, 20, 6, 15]
然后,我以最高价格订购totalPaymentperPerson --> [25,20,15,6]
因此nameArray变为[Me, Dad, Sister, Mum]
(所有价格和名称均由用户动态添加)
因此,现在总费用为:66
每人的价格为:16.5 --> 66/4
debtorArray [Sister, mum] --> the pay 15 and 6, under the cost per person of 16.5
receiverArray[Me, Dad] --> [20.5, 3,5]
differenceArray[1.5, 10.5] ---> cpp - debtorArray
现在我必须做这样的事情:
我不知道该如何实现。如果我为3个参与者创建一个公式,那么如果我有6个参与者,则该公式不再起作用..或者如果我有3次付款,它可能会起作用,但不是5 ..有什么办法可以做到逻辑吗?我的代码中有太多“ if-else” ...
答案 0 :(得分:0)
考虑以下输入数据/相似项[注意:我对您的输入进行了一点更改]:
Me = 25
Dad = 20
Mum = 6
Sister = 15
下面是将金额平均分配给彼此的Java代码:
package com.shree.algo;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class EvenDistribution {
private ConcurrentHashMap<String,Double> initialPayment = new ConcurrentHashMap<>();
private ConcurrentHashMap<String,Double> computations;
public EvenDistribution(Map<String,Double> initialPayment){
this.initialPayment.putAll(initialPayment);
computations = new ConcurrentHashMap<>();
subtract();
}
private double getAmoutToDistribute(){
double totalAmount = 0;
for(double credit: initialPayment.values()){
totalAmount = totalAmount + credit;
}
double amountToDistribute = (totalAmount/initialPayment.size());
return amountToDistribute;
}
public void subtract(){
double amountToDistribute = getAmoutToDistribute();
for(String name: initialPayment.keySet()){
double remainingAmount = initialPayment.get(name) - amountToDistribute ;
computations.put(name, remainingAmount);
}
}
public void calculate(){
for(String name: computations.keySet()){
Double p1amount = computations.get(name);
if(p1amount>0){
for(String tmpName: computations.keySet()){
double p2amount = computations.get(tmpName);
if(!tmpName.equals(name) && p2amount<0){
double result = p1amount + p2amount;
computations.put(name, 0D);
computations.put(tmpName, result);
System.out.println(name + "=>" + p1amount + "=>" + tmpName);
break;
}
}
}
}
for(String name: computations.keySet()){
if(computations.get(name)!=0){
calculate();
}
}
}
}
主类:
package com.shree.algo;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String,Double> initialPayment = new HashMap<>();
initialPayment.put("Me", 25D);
initialPayment.put("Dad", 20D);
initialPayment.put("Mum", 6D);
initialPayment.put("Sister", 15D);
EvenDistribution evenDistribution= new EvenDistribution(initialPayment);
evenDistribution.calculate();
}
}
输出:
Dad=>3.5=>Mum
Me=>8.5=>Mum
Mum=>1.5=>Sister