java - 如何优雅地以各种顺序调用方法?

标签 java python algorithm

我有四种方法:

right();
up();
left();
down();

然后我按以下方式调用它们:

result = right();
if checkResult(result)
  return(result);

result = up();
if checkResult(result)
  return(result);

result = left();
if checkResult(result)
  return(result);

result = down();
if checkResult(result)
  return(result);

所以这是优先事项。我知道其中之一会起作用。但我需要根据优先级检查它:[right, up, left, down]

现在,诀窍是:我的优先级会随着时间而改变。确切地说,这取决于之前的举动。所以:

if previous move was up(), then priority is [right, up, left, down]
if previous move was left(), then priority is [up, left, down, right]
if previous move was down(), then priority is [left, down, right, up]

所以你可以清楚地看到这里的逻辑。问题是:如何调用给定(可变)优先级的函数?

显然,我可以只执行切换和复制粘贴调用 block ,但这很丑陋。那么这是一种优雅的方式吗?

再者,Java和Python的方法是什么?

最佳答案

我会为方法分配整数 ID,例如:

right() - 0
up() - 1
left() - 2
down() - 3

我会将 previousMove 存储为一个整数,该整数与调用的最后一个方法相对应。因此,无论何时调用 up(),previousMove 都等于 1,等等。(您可以根据需要的逻辑在任何需要的地方进行设置)

然后我会循环如下:

public class Test {
    public static void main(String[] args) {
        int previousMove = 3; //Change this to test

        int startMethod = previousMove - 1 < 0 ? 3 : previousMove - 1; //Represents the ID of the method before the previousMove, accounting for negative values and wrapping around
        int offset = startMethod - 1 < 0 ? 3 : startMethod - 1; //Represents the ID of the method before the startMethod, accounting for negative values and wrapping around

        for (int i = startMethod; true; i++) {
            if (i > 3) i = 0; //Wrap around
            switch (i) {
                case 0: right(); break;
                case 1: up(); break;
                case 2: left(); break;
                case 3: down(); break;
            }
            if (i == offset) break; //Break once all 4 methods have been called
        }
    }

    private static void right() {
        System.out.println("Calling right");
    }

    private static void up() {
        System.out.println("Calling up");
    }

    private static void left() {
        System.out.println("Calling left");
    }

    private static void down() {
        System.out.println("Calling down");
    }
}

previousMove = 3(向下)的输出:

Calling left
Calling down
Calling right
Calling up

解释:我们从 startMethod(previousMove 之前的一个)一直循环到 4 个方法,直到调用完所有方法。因此,如果您的“前一步”是 left() 方法,例如,您可以将 previousMove 设置为 2,并且循环将根据需要调用第 1、第 2、第 3 和第 4 种方法。

一开始你可能很难理解整数,但我可以向你保证,通过尝试理解上面的代码,而不是仅仅将其复制粘贴到你的程序中,你会受益匪浅:)

关于java - 如何优雅地以各种顺序调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28776447/

相关文章:

Java内省(introspection)和反射

java - 使用 DigestInputStream 从同一个 InputStream 计算多个校验和

java - 向数组添加增量?

python:为什么random.shuffle改变数组

python-3.x - 使用 def 函数将五进制转换为十进制、十进制转换为五进制、5 进制数相加和 5 进制数相乘

Java : Strictly type checking fails?

python - 如何将包含多个值和逗号的变量写入 csv 文件?

python - 在 Python numpy 掩码数组中用最近的邻居填充缺失值?

algorithm - 具有两个约束的背包问题的伪代码算法

c++ - 优化代码 - CPU 与内存