[英]How to Find all Pairs in an Array of Integers Whose sum is Equal to a Given Number
[英]Checking all possible expressions that equal a certain number given 4 integers?
大家好,我非常感謝我的程序提供的任何幫助。 在該程序中,我必須要求用戶輸入4個整數,並且必須輸出一個等於24的可能的表達式(很多)。如果沒有這樣的解決方案,我也必須告訴用戶。 到目前為止,這就是我所擁有的:
import java.util.Scanner;
public class Game24 {
public static void main(String[] args) {
System.out.println("Enter 4 numbers and hit enter after each number: ");
Scanner input = new Scanner(System.in);
String num1 = input.nextLine();
String num2 = input.nextLine();
String num3 = input.nextLine();
String num4 = input.nextLine();
StringPermutation("", num1 + "+" + num2 + "*" + num3 + "/" + num4 + "(" + ")");
}
public static String StringPermutation(String x, String y) {
double expression = 0;
int count = 0;
if (y.length() <= 1) {
try {
for (int i = 0; i < y.length(); i++) {
String p = y.substring(0, i) + y.substring(i + 1);
expression = Double.parseDouble(StringPermutation(x + y.charAt(i), p));
}
if (y.length() <= 1 && expression == 24) {
do {
count++;
System.out.println(x + y);
} while (count < 1);
}
//if (y.length() <= 1 && expression != 24) {
// System.out.print("No solution");
//}
} catch (Exception e) {}
} else {
for (int i = 0; i < y.length(); i++) {
String p = y.substring(0, i) + y.substring(i + 1);
StringPermutation(x + y.charAt(i), p);
}
}
return "";
}
}
所以我想做的是將所有輸入的用戶排列都作為字符串。 然后將字符串解析為雙精度,並檢查所有可能的排列以查看它們是否等於24,以及是否將表達式輸出為字符串。 但是,這對我不起作用。 當我運行程序時,沒有任何顯示。 另外,如果我取消注釋部分,則不會顯示任何內容。
以下是一些設計提示,可能會幫助您入門:
構建解決方案列表的遞歸方法的一般形式如下:
列表解決方案= new ArrayList <>(); 測試(partialSolution,startingContext);
私用無效測試(Solution currentSolution,Context currentContext){如果(currentContext.isNotEmpty()){for(每個步驟){test(currentSolution.add(step),currentContext.remove(step)); }} if(currentSolution.isSuccessful()){solutions.add(currentSolution); }}
在您的情況下,每個“步驟”都涉及排列的2個維度。 第一維是嘗試所有剩余的操作數。 在不創建多個數組的情況下執行此操作的一種簡單方法是始終使用第一個操作數,然后使用連續的數組成員進行切換。 第二個維度是每個運算符(* +-/)。 這里最簡單的事情是只有4個test調用。 更完整的抽象方法是將運算符放在一個單獨的枚舉中,但這可能對您的情況有些過分。
所以這是一些入門的部分代碼
class Expressions {
private final Set<String> validExpressions = new TreeSet<>();
public Expressions(int expectedResult, int... operands) {
test("" + operands[0], operands[0], Arrays.copyOfRange(operands, 1, operands.length);
}
private void test(String currentExpression, int currentResult, int... operands) {
if (operands.length > 0) {
...
} else if (currentResult == result) {
validExpressions.add(expression + " = " + result);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.