我必须编写一段代码,该代码从Scanner对象接受1到9之间的4个整数的输入,并以任何方式将它们组合为等于24。尽管我的解决方案不是最好的,但我已经设法使用变量b、c、d编译了许多if语句,并希望将用户输入的数字存储在一个数组中,并交换a、b、c、d的值以生成每种可能的数字组合
例如,一个配对可能是(a+b*c) -d= 24。我想要为所有可能的组合切换a,b,c,d的值,但无论如何我都不知道该怎么做。这就是我的东西
public static void daGame(int a, int b, int c, int d) {
int[] baseArray = {a, b, c, d};
int [] keyArray = baseArray.clone();
if(a > 9 || b > 9 || c > 9 || d > 9 || a == 0 || b == 0 || c == 0 || d == 0){
System.out.println("You entered a number greater than 9 or you enterered 0:");
main(null);
System.exit(0);
}
for(int i = 0; i < 2; i++){
for(int j = 0; j < baseArray.length; j++){
if(i == 1){
baseArray = keyArray.clone();
int temp = baseArray[0];
baseArray[0] = baseArray[3];
baseArray[3] = temp;
j = baseArray.length - 1;
}
else if (i == 2){
baseArray = keyArray.clone();
int temp = baseArray[1];
baseArray[1] = baseArray[0];
baseArray[0] = temp;
temp = baseArray[2];
baseArray[2] = baseArray[3];
baseArray[3] = temp;
j = baseArray.length - 1;
}else{
int temp = baseArray[j];
baseArray[j] = baseArray[baseArray.length - (1+j)];
baseArray[baseArray.length - (1+j)] = temp;
这遗漏了很多可能的组合。
发布于 2014-12-02 06:31:21
这里有一种方法可以做到。只需在算术运算和数字上都使用permutation
方法。
一旦您有了来自用户的输入,就将它们转换为字符串:
void perm(std::string str, std::vector<std::string> &vec){
perm("", str, vec);
}
void perm(std::string prefix, std::string str, std::vector<std::string &vec){
int n = str.length();
if( n == 0 ) vec.push_back(str);
for(int i = 0; i < n; i++){
perm(pre+ str[i], str.substr(0,i) + str.substr(i+1,n), vec);
}
}
现在您有了一个置换方法,假设您有来自输入的字符串:1234
,您可以对该字符串进行置换以获得2134 3214 1243 ... etc
你也可以对算术运算做同样的事情,比如+-*/
或者,您可以组合以下操作:
std::vector<std::string> vec;
perm("1234" + "*-/+", vec);
现在,您有了一个包含数字和运算的所有排列的向量。现在,您可以将列表修剪为只接受number operation number operations
。这可以使用正则表达式来完成:
`\d[*|+|-|/]\d[*|+|-|/]\d[*|+|-|/]\d[*|+|-|/]`
Then disregard the last operation.
现在您有了所有的排列,就像strings
一样。创建一些逻辑将其转换回ints
注意:
这里有浪费的空间,但是这个方法应该可以工作。
https://stackoverflow.com/questions/27238230
复制相似问题