Gab*_*und 5 java algorithm math
我正在编写一个程序,它接受4个数字作为输入,然后尝试查看加法减法除法和四个数字相乘的组合是否可以使它们等于24.我的方法是为四个数字的每个可能组合创建一个方法数字和四个操作数,有点冗长.以下是2种方法的示例.
public static boolean add(int a, int b, int c, int d){
boolean adBool;
adBool = a + b + c + d == 24;
return adBool;
}
public static boolean sub1(int a, int b, int c, int d){
boolean subBool1;
subBool1 = a - b - c - d == 24;
return subBool1;
}
Run Code Online (Sandbox Code Playgroud)
然后在我的Main中我为每个方法创建一个while循环,如果方法返回true,将打印它停止的方法,是解决方案.这是一个例子.
while (add(num1, num2, num3, num4)){
System.out.println("Your solution is " + num1 + " + " + num2 + " + " + num3 + " + " + num4 + " = 24\nCongratulations!");
break;
}
while (sub1(num1, num2, num3, num4)){
System.out.println("Your solution is " + num1 + " - " + num2 + " - " + num3 + " - " + num4 + " = 24\nCongratulations!");
break;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法存储操作数,如+和 - 所以我可以把它们放在一个数组中,只是使用一些嵌套的for循环来写这个?
假设操作数是固定的,您可以创建一个生成器,该生成器转储可能的运算符,并将它们传递给评估器以确定它们是否为真。
while (generator.hasNext()){
Operators ops = generator.getNext();
if evaluatesTo(operand1, operand2, operand3, operand4, 24, ops){
// print it
}
}
Run Code Online (Sandbox Code Playgroud)
一个简单的生成器可以这样完成:
List<String> list = new ArrayList<String>();
list.add("+++");
list.add("++-");
...
Iterator generator = list.iterator();
Run Code Online (Sandbox Code Playgroud)
其中生成器实现了 java.util.Iterator 接口,该接口使用所有运算符 (+-*/) 进行初始化,并转储出大小为 3 的所有排列。
evalutesTo 方法简单地计算它:
public boolean (int operand1, int operand2, int operand3, int operand4, int total, Operators ops ){
// calculate operand1 "ops.get(0)" operand2 "ops.get(1)" operand3 "ops.get(2)" operand4 == total
}
Run Code Online (Sandbox Code Playgroud)
所以如果 ops 是 [+-/] 它会检查
if (operand1 + operand2 - operand3 / operand4 == 24) return true;
Run Code Online (Sandbox Code Playgroud)
我应该补充一点,您可以稍后添加各种效率,但您的问题是如何通过更好的策略来做到这一点。其他用户对细节有一些评论,但我现在不担心。首先你需要建立这样的框架,然后你就可以关心细节了。最关键的是,您不需要创建数百个看起来相似的方法。