使用来自数组的串联整数创建字符串时遇到问题

时间:2019-10-25 18:41:51

标签: java greedy

这是一个使用贪婪方法将货车装满大篷车的重量加载程序。 我试图将数组中的Integer元素连接到必须遵循此模式的字符串输出中。

```
(wagon capacity) -> (weights of packages in wagon) = (total weight of the wagon)
100 –> (70, 25) = 95
200 -> (100, 90) = 190
140 –> (78, 60) = 138
600 –> (600) = 600
```

现在我的代码对我的容量和权重进行排序(降序),并将它们添加到onBoard变量中,当我尝试打印时,它可以正确显示容量,但未连接我的权重,而同时重用第一重。这是我的代码,任何反馈将不胜感激。

```
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    Integer[] cartCapacity = {100, 200, 140, 600};
    Integer[] cargoTons = {50, 60, 70, 100, 50, 41, 25, 78, 90, 41, 600};

    /*Desired output
     *(wagon capacity) -> (weights of packages in wagon) = (total weight of the wagon)
     * 100 –> (70, 25) = 95
     * 200 -> (100, 90) = 190
     * 140 –> (78, 60) = 138
     * 600 –> (600) = 600
     * 
     * Current output
     * 600->{600}
     * 200->{600}
     * 140->{600}
     * 100->{600}
     */

    //Sorting Carts
    Arrays.sort(cartCapacity, Collections.reverseOrder());
    //Sorting package tonnage
    Arrays.sort(cargoTons, Collections.reverseOrder());


    //After sorting carts
    System.out.println("The carts capacities are: ");
    for (int i = 0; i < cartCapacity.length; i++) {
        System.out.println(cartCapacity[i]);
    }


    System.out.println();


    //After sorting package tonnage
    System.out.println("The packages weights are: ");
    for (int i = 0, k = 0; i < cargoTons.length; i++) {
        System.out.println(cargoTons[i]);
    }


    int cartOnBoard = 0;
    int cartIdx = 0;
    String cartElements = "";
    while (cartIdx < cartCapacity.length) {
        for (int i = 0; i < cargoTons.length; i++) {
            if (cartOnBoard + cargoTons[i] <= cartCapacity[cartIdx]) {
                cartOnBoard += cargoTons[i];
                cartIdx++;
                cartElements += Integer.toString(cartOnBoard);
                System.out.println(Integer.toString(cartCapacity[i]) + "->{" + cartElements + "}");
            } 
            else
                System.out.println(Integer.toString(cartCapacity[i]) + "->{" + cartElements + "}");
        }
    }
    }
```

1 个答案:

答案 0 :(得分:1)

存在多个问题,这是带有注释的固定循环:

int cartIdx = 0;
while (cartIdx < cartCapacity.length) {
    int cartOnBoard = 0; // this should be initialized for every cart
    String cartElements = ""; // this should be initialized for every cart
    for (int i = 0; i < cargoTons.length; i++) {
        if ((cartOnBoard + cargoTons[i]) <= cartCapacity[cartIdx] && cargoTons[i] > 0) {
            cartOnBoard += cargoTons[i];
            cartElements += Integer.toString(cargoTons[i]) + ",";
            cargoTons[i] = -1; // you need to mark used cargos
        }
    }
    System.out.println(Integer.toString(cartCapacity[cartIdx]) + "->{" + cartElements + "}"); // print one line per cart, not per every cargo
    cartIdx++;
}