贪婪算法-想法不对

时间:2018-12-14 12:20:35

标签: java arraylist jpanel

我正在做一个“丝带包装”个人项目,但被困住了。

我有N个随机大小的块。我需要将所有N个块都放在功能区中,以使其具有最小的高度。

This is the visual result I currently get (without the part of the else)

一切都对功能区中的第一行有效,问题是当它需要在功能区中已有的图块上打印其他图块时。我尝试了几件事,但还是没做(我将下面的最后一个“版本”放在下面)。

public void algoGlouton(Graphics g) {

    ArrayList<Bloc> listBlocRemaining = (ArrayList<Bloc>) blocksList.clone(); 

    int offsetX = 13;
    int offsetY = 600;
    int widthAvailable= 0;
    int smallestHeight= 300;

    for (Bloc b : blocksList.clone) {
        if(widthRemaining + b.getWidth () < ribbon.getWidth ()) {
            widthAvailable += b.getWidth();

            g.setColor(b.getColor());
            g.fillRect(offsetX, offsetY - b.getHeight(), b.getWidth(), b.getHeight());
            listBlocksIntoRibbon.add(b);

            b.setX(offsetX);
            b.setY(offsetY - b.getHauteur());
            offsetX += b.getLargeur();

        } else { //Below is the mess
            // We search the smallest height
            for (Bloc b1 : listBlocksIntoRibbon) {
                if (b1.getHauteur() < smallestHeight) {
                    //when we have the smallest, we go through the blocks remaining
                    for (Bloc b2 : listBlocRemaining) {
                        // PlaceRemaining is an int into the block class and its equal to his width
                        // we see if the block can fit above the smallest height
                        if (b1.getPlaceRemaining() > b2.getWidth()){
                            b2.setX(b1.getX());
                            b2.setY(b1.getHeight() - b2.getHeight());

                            g.setColor(b.getColor());
                            g.fillRect(b1.getX(), b1.getHeight() - b2.getHeight(), b2.getWidth(), b2.getHeight());              
                        }
                    }
                }
            }
        }
    }

我现在真的迷路了,我尽力解决了这个问题,但是我需要一些帮助以进一步解决问题。

0 个答案:

没有答案