【发布时间】:2019-04-30 17:37:24
【问题描述】:
我正在使用 Java 基于线性方程计算 PayStructure 中各种 Paycode 的值。我的不同方程如下:
CTC = Fixed Value
Basic = CTC * 0.4
HRA = Basic/2
ConveyanceAllowance = Fixed Value
ProvidentFund = Basic * 0.12
Gratuity = Basic * .0481
OtherAllowance = (CTC - (Basic + HRA + ConveyanceAllowance + ProvidentFund + Gratuity))
我已经尝试使用here 给出的解决方案。但是这个解决方案只有在所有计算值都是整数的情况下才有效,在我的情况下,这些值也可以包含十进制数字。我根据上述条件修改的代码如下:
public class PayStructure {
public static void main(String[] args) {
findAndprintSolutions(1, 1000000);
}
private static void findAndprintSolutions(int from, int to) {
for (int a = from; a < to; a++) {
for (int b = from; b < to; b++) {
for (int c = from; c < to; c++) {
for (int d = from; d < to; d++) {
for (int e = from; e < to; e++) {
for (int f = from; f < to; f++) {
for (int g = from; g < to; g++) {
if (isSolution(a, b, c, d, e, f, g))
printSolution(new int[] { a, b, c, d, e, f, g });
}
}
}
}
}
}
}
}
private static boolean isSolution(int a, int b, int c, int d, int e, int f, int g) {
if (a != 100000)
return false;
if (b != a * (.4))
return false;
if (c != b / 2)
return false;
if (d != 10000)
return false;
if (e != b * (.12))
return false;
if (f != b * (.0481))
return false;
if (g != (a - (b + c + d + e + f)))
return false;
return true;
}
private static void printSolution(int[] variables) {
StringBuilder output = new StringBuilder();
for (int variable : variables) {
output.append(variable + ", ");
}
output.deleteCharAt(output.length() - 1);
output.deleteCharAt(output.length() - 1);
System.out.println(output.toString());
}
}
此外,上述代码将被终止,因为 CTC 的最大值可能为数百万,并且根据变量的数量,时间复杂度最终将达到millions^NumberOfVariables。是否有任何其他可能性来计算基于给定方程的值?方程和变量的数量可能会有所不同,但会有一个解决方案来计算每个变量的值,因此通用解决方案的任何输入都会更好。
E.g.: If CTC = 100000 and ConveyanceAllowance = 10000, the code should return the output as:
Basic = 40000
HRA = 20000
ProvidentFund = 4800
Gratuity = 1924
OtherAllowance = 23276
【问题讨论】:
-
这似乎是一个询问算法的问题,而不是一个关于如何实现特定算法的问题。因此,应该在Computer Science Stack Exchange 上询问。
-
Basic = CTC * 0.4 时,Basic = 0 怎么办?对于 Basic = 0,CTC 需要为 0,这是不可能的。
-
@user3386109:谢谢你指出,我已经修正了值。
-
所以还不清楚的是:你想完成什么?给定
CTC和ConveyanceAllowance,计算其他值是简单的数学运算。 -
我发布了一个简单的示例,其中几乎所有组件都依赖于 Basic。如果以下组件依赖于上述组件怎么办?例如:基本 = CTC * (0.4)、ConveyanceAllowance = 10000、HRA = (Basic/2) + ConveyanceAllowance、ProvidentFund = HRA * 0.2、小费 = (ProvidentFund * 0.1) + ConveyanceAllowance、OtherAllowance = CTC - (Basic+HRA+ProvidentFund +运输津贴+小费)。如何以编程方式解决上述方程是我正在寻找的?