0

我正在尝试进行 First-Fit bin 包装。这是我编写的代码,每行都有注释作为注释:

private void runFirstFit(ActionEvent event) {
    // The counters
    int i;
    int j = 0;

    // The boolean
    packingComplete = false;

    // Declare an arrayList from the numbers the user has entered
    ArrayList<Integer> numbers = new ArrayList(6);

    // Add numbers into the array from input (using a loop)
    for (i = 0; i < 6; i++) {
        numbers.add(parseInt(getNumber(i)));
    }

    // - Main packing algorithm starts here -
    // Iterate through arraylist and get next number
    Iterator<Integer> iterator = numbers.iterator();

    // While there are still numbers left, try and add to bins
    while (iterator.hasNext()) {
        // Number(s) still exist in the list
        // Check if number can fit inside bin
        System.out.println("Number currently in queue: " + iterator.next());

        if (canNumberFitInsideBin(j, iterator.next())) {
            // Put number inside bin
            bin[j] += String.valueOf(iterator.next()) + ", ";

            System.out.println("Number added to bin " + j);
        } else {
            // Bin is full, move to the next bin (increment counter)
            j++;

            // Put number inside that bin
            bin[j] += String.valueOf(iterator.next()) + ", ";

            System.out.println("Counter incremented");
        }
    }

    // Update all labels
    updateAllBinLabels();
}

基本上,该getNumber(i)部分是一个返回数字的函数。我正在使用循环将实际数字(其中 6 个,更具体地说)添加到称为“数字”的 ArrayList 中。

我已经尝试在每个阶段打印出数字并查看它正在处理的数字 - 但它似乎只是无缘无故地随机跳过了一些数字。例如,对于1,2,3,4,5,6它添加到的第一个数字的 ArrayList 输入bin[0]3(应该是1),然后它还添加6bin[0]并忽略所有其他数字并进入下一个 bin 数组。

谁能发现我做错了什么?

谢谢

4

1 回答 1

2

最明显的问题是 iterator.next() 每次进入循环只能调用一次。每次调用它时,您都会在列表中前进。您需要调用一次并将其保存在循环顶部的临时变量中。

此外,您可能应该检查该数字是否可以放入 else 中的下一个 bin,除非您知道没有一个值大于您的 bin 大小。

于 2014-03-29T00:58:24.863 回答