我要做的是打印一个从末尾开始递增的递增集(参见下面的示例)。
我所拥有的代码采用了一组操作符并逐一更改它们,从最后开始并向后工作。这就是我所拥有的(mut是变异):
public static void main(String[] args) {
String[] set = {"*", "*", "*"};
int numOfMuts = 6;
int currMutIndex = set.length - 1;
String currOp = set[currMutIndex];
String nextMut = currOp;
for (int i = 1; i <= numOfMuts; i++) {
nextMut = shiftOperator(nextMut);
if (nextMut.equals(currOp)) {
set[currMutIndex] = currOp;
if ((currMutIndex--) == -1) {
break;
}
currOp = set[currMutIndex];
nextMut = shiftOperator(currOp);
}
set[currMutIndex] = nextMut;
//print out the set
printSet(set);
}
}
/*
This method shifts the operator to the next in the set of
[*, +, -, /]. This is the order of the ASCII operator precedence.
*/
public static String shiftOperator(String operator) {
if (operator.equals("*")) {
return "+";
} else if (operator.equals("+")) {
return "-";
} else if (operator.equals("-")) {
return "/";
} else { //operator is "/"
return "*";
}
}
这给了我:
*, *, +
*, *, -
*, *, /
*, +, *
*, -, *
*, /, *
但我想要的是:
*, *, +
*, *, -
*, *, /
*, +, *
*, +, +
*, +, -
用更简单的术语解释问题,使用数字:
1, 1, 1 1, 3, 1
1, 1, 2 1, 3, 2
1, 1, 3 1, 3, 3
1, 1, 4 1, 3, 4
1, 2, 1 1, 4, 1
1, 2, 2 1, 4, 2
1, 2, 3 1, 4, 3
1, 2, 4 1, 4, 4
1, 3, 1 2, 1, 1
1, 3, 2 2, 1, 2
依此类推,我希望产生的突变数量。我怎么需要修改算法或者(我确定有)更简单的方法来实现这个目标?我甚至不确定我要问的名字,所以请根据需要标记。
答案 0 :(得分:0)
基本上,你要做的是计入第四纪。就像二进制数字的结构一样:
2^(n-1) 2^(n-2) ... 2^1 2^0
会导致:0,1,10,11,100等等。
第四纪系统将使用相同的方式计算:
4^(n-1) 4^(n-2) ... 4^1 4^0
这将导致:0,1,2,3,10,11,12,13,20等等。您可以对任何数字系统执行相同操作。这里有一些代码可以满足您的要求:
String set[] = new String[3];
String countSymbols[] = {"*", "+","-","/"}
/* You can set to however far you want to count here, but in your code,
the limit would be (4^3)-1 = 3*(4^2)+3(4^1)+3*(4^0) = 63. We get this
because there's 4 symbols and 3 digits. */
for (int i = 0 ; i < 64 ; i++) {
/* Since you're trying to print them in increasing order, we'll have to set
the values in reverse order as well. */
// 4^0 = 1
set[2] = countSymbols[i%4];
// 4^1 = 4
set[1] = countSymbols[(i/4)%4]
// 4^2 = 16
set[0] = countSymbols[(i/16)%4]
printSet(set);
}
希望这有帮助。