【问题标题】:How to change one Boolean based on values found in ArrayList?如何根据 ArrayList 中的值更改一个布尔值?
【发布时间】:2013-12-01 20:43:29
【问题描述】:

我正在尝试制作一个演绎算法来解决数独难题。我的板由 ArrayList 中的 81 个节点组成。 - 每个节点都有一个布尔值 如果我的算法(称为 CRME)发现至少有一个节点的布尔值(hasChanged)等于 true,我希望我的算法(称为 CRME)继续尝试解决难题,但我不确定如何执行此操作。 canChange 也是该方法所在类中的全局变量。

public void CRME() {
    canChange = true;
    while (canChange == true) {
        for (Node node : cells) {
            scanColumn(node);
            scanRow(node);
            scanMiniGrid(node);
        }
    }

}

    public void scanRow(Node n){
    for(Node node : cells){
        int arraySize = node.posVals.size();
        ArrayList<Integer> toRemove = new ArrayList<Integer>();
        if(node.get_ROW_ID() == n.get_ROW_ID()){
            toRemove.add(node.getValue());
        } 
        n.posVals.removeAll(toRemove);
        if(arraySize < node.posVals.size()){
            node.hasChanged = true;
        }
    }
}

这是 scanRow 方法,另外两个类似命名的方法是相同的,只是语法发生了明显变化,例如 node.get_ROW_ID();将是 node.get_COL_ID();。

【问题讨论】:

  • 不知道你想达到什么目的,但我可以看到一个可能的无限循环。

标签: java arraylist while-loop boolean sudoku


【解决方案1】:

我假设你有一个静态变量

static boolean hasChanged; // in the Node class

所以你可以使用:

 node.hasChanged = true;

或者你可以创建 hasChange 方法来设置变量,像这样

boolean hasChanged;

public void hasChanged(boolean val){
    this.hasChanged = val;
}

并在循环中使用,如下所示:

hasChanged(true); or hasChanged(false);

【讨论】:

    【解决方案2】:

    并不是说您的方法是最好的,但是如果您尝试简单地继续,而 hasChanged 之一是 true 对于您的任何节点,以下就足够了:

    public void CRME() 
    {
        goOn = false;
    
        for (Node node : yourArrayListOfNodes) 
        {
            if (node.hasChanged)
            {
               goOn = true;
               break;
            }
        }
    
        if (goOn)
        {
            //Insert Whatever code you want to run after the check
            //.........................................
    
            //Use recursion to repeat process
            //Note recursive call will only take place if goOn is true
            CRME()
        } 
    }
    

    这似乎是您想要做的,请注意,如果您的逻辑不正确,您可以获得StackOverflowError,因为您会继续进行递归调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2021-03-12
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多