【问题标题】:First-Fit Bin Packing Algorithm Skipping NumbersFirst-Fit Bin Packing 算法跳过数字
【发布时间】:2014-03-29 00:48:49
【问题描述】:

我正在尝试进行 First-Fit 垃圾箱包装。这是我编写的代码,每行都解释为 cmets:

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),然后它还将 6 添加到 bin[0] 并忽略所有其他数字并转到下一个 bin 数组。

谁能发现我做错了什么?

谢谢

【问题讨论】:

    标签: java javafx bin-packing


    【解决方案1】:

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

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

    【讨论】:

    • 在程序的初始阶段,它不会让用户输入大于 bin 大小的数字。我使用了不同的方法来存储数字——使用普通数组而不是数组列表,我的代码现在可以工作了。但是,由于某种原因,移动 iterator.next() 会使程序停留在第一个数字上。
    猜你喜欢
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多