1

我想要做的是打印出一个从末尾递增的递增集(参见下面的示例)。

我拥有的代码采用一组运算符并逐个更改它们,从最后开始并向后工作。这是我所拥有的(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

等等,对于我想要产生的突变数量。我需要如何修改算法或者有什么(我确定有)更简单的方法来实现这一点?我什至不确定我要问的名称,所以请根据需要标记。

4

1 回答 1

1

基本上,您要做的是计算第四纪。就像二进制如何构造为数字一样:

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);
    }

希望这可以帮助。

于 2013-10-04T02:30:09.217 回答