预测这组固定结果的最优雅方法是什么?

时间:2017-04-28 07:08:47

标签: java

假设您有一组固定的结果,如下图所示:

outcomes

列号代表将要发生的四个阶段 每一行都是四个阶段的可能结果。

例如:如果第一阶段是PURPLE而第二阶段是ORANGE,第三阶段将是蓝色,第四阶段将是红色。

我已经能够通过一个非常复杂的if / else语句来完成这个,但我想知道是否有更好的方法?

编辑:必须在第一阶段之后进行预测,并且应该为第二阶段返回两种可能性。

3 个答案:

答案 0 :(得分:1)

如果您希望根据第一个和第二个获得第三个和第四个,只需构建一个地图:

Map<String, String> map = new HashMap<>();
map.put("BR", "OP");
map.put("BP", "RO");
// ...

其中BROP分别代表蓝色,红色,橙色和紫色。然后你可以查询一下,例如

String thirdAndFourth = map.get("BP");

请注意,其他一些结构可能比字符串更好,例如

class ColorPair {
  Color first;
  Color second;
}

但这个想法是一样的:

Map<ColorPair, ColorPair> map = new HashMap<>();
// Populate map...

ColorPair thirdAndFourth = map.get(firstAndSecond);

答案 1 :(得分:0)

我有一个6x4的颜色数组,并快速循环找到与前两种颜色相匹配的行。循环六行检查数组中前两个条目的值不会是复杂的代码或性能问题。

答案 2 :(得分:0)

预存结果的递归方法怎么样, 在开始处理输入之前调用setup()。

// Pre known outcomes
List<String> outcomes;
// To track the inputs as we move on through them
public static StringBuilder inputStore = new StringBuilder();
// To track no of inputs expected overall
public static int counter = 0;
// Method for processing next input recursively
public static void next(int input){
    // Appending is to track each input
    inputStore.append(input);
    counter++;
    if(counter == noOfInputsExpected){
        // Process inputStore
        String s1 = inputStore.toString();
        for(String s : outcomes){
            // Check if the inputs collected match the defined ones
            if(s.equals(s1))
                //Process outcome
        }
        return;
    }
    else if(input == 1 || input == 2 || input == 3 || input == 4){
        // In case of valid input move on
        // We can even separate each one as a else for mid step processing
        next(getNextInput());
    }
    else{
        // Bad input, take some action
    }
}

public static void setup(){

    // Assuming inputs, are {1234, 1324, ... some permutations in you know}
    outcomes = new ArrayList<String>(noOfPermutationsRequired);
    //Put all the known possibilities
    ...
    outcomes.add("1234");
    outcomes.add("1324");
    ...
}
相关问题