如何减少java中的圈复杂度?

时间:2016-12-07 09:45:32

标签: java complexity-theory reduce

如何在java中减少此函数的圈复杂度?:

public void execute() {

        if (dx == 1 && dy == 0) { this.moveRight();}
        if (dx == -1 && dy == 0) { this.moveLeft();}
        if (dx == 0 && dy == -1) { this.moveUp();}
        if (dx == 0 && dy == 1) { this.moveDown();}
        if (dx == 1 && dy == -1) { this.moveUpRight();}
        if (dx == 1 && dy == 1) { this.moveRightDown();}
        if (dx == -1 && dy == -1) { this.moveLeftUp();}
        if (dx == -1 && dy == 1) { this.moveDownLeft();}
}

2 个答案:

答案 0 :(得分:2)

我认为以下在圈复杂度方面不太复杂:

public void execute() {
    if (dx ==  0) {this.moveVerticaly(dy)}
    if (dx ==  1) {this.moveRight(dy)}
    if (dx == -1) {this.moveHorizontaly(dy)}
}

答案 1 :(得分:2)

考虑将dxdy转换为唯一值并switch在其上:

switch ((dx + 1) * 4 + (dy + 1))

switch跳跃在时间上实际上是恒定的,代价是switch表达式的计算。

case 1对应dx == -1dy == 0,依此类推。