0

基本上我正在尝试为多维背包问题创建模拟退火的实现。我在让系统决定是否接受较低值的状态时遇到问题。退火由这个函数控制:

while (this.temp > 0)
    {
        System.out.println("Temperature: "+this.temp);
        System.out.println("Current bag: "+bagString(currentBag)+" (Value "+problem.getValue(currentBag)+")");
        next = getNext();
        System.out.println("Next bag: "+bagString(next)+" (Value "+problem.getValue(next)+")");
        if (acceptNext(next))
        {
            System.out.println("Accepted");
            this.currentBag = next;
        } else {
            System.out.println("Not accepted");
        }
        this.temp -= this.delta;
    }

acceptNext() 函数决定是否接受下一个状态,定义如下:

public boolean acceptNext(ArrayList<Boolean> next)
{
    if (problem.getValue(next) > problem.getValue(this.currentBag))
    {
        return true;
    } else {
        int loss = (problem.getValue(this.currentBag) - problem.getValue(next));
        double prob = Math.exp(loss/this.temp);
        Random generator = new Random();
        double selection = generator.nextDouble();
        System.out.println("Prob: "+prob+", random number: "+selection);
        if (selection < prob) {
            return true;
        }
        return false;
    }
}

经过一番测试,我发现 currentBag 字段在调用 acceptNext() 函数之前被赋值为下一个值。我在我的任何代码中都找不到另一个“this.currentBag = next”。为了完整起见,这里是 getNext() 函数:

public ArrayList<Boolean> getNext()
{
    Random generator = new Random();
    boolean valid = false;
    ArrayList<Boolean> next = new ArrayList<Boolean>();
    int j;
    while (!valid)
    {
        next = this.currentBag;
        j = generator.nextInt(problem.getNumObjects());
        if (next.get(j) == true)
        {
            next.set(j, false);
        } else {
            next.set(j, true);
        }
        if (problem.isValid(next))
        {
            valid = true;
        }
    }
    return next;
}

我看不出是什么使这个值更新。有人在代码中看到任何东西吗?

谢谢

4

2 回答 2

3

执行此操作时,next 指向与当前包相同的内容,因此对 next 的所有更改都会反映在 currentBag 中。在您的 getNext() 方法中:

while (!valid)
{
    next = this.currentBag;
    ...
}

试试这个:

while (!valid)
{
    next = new ArrayList<Boolean>(this.currentBag);
    ...
}
于 2010-04-09T13:36:27.363 回答
1

getNext() 设置 next 以引用 currentBag 对象,然后对其执行设置操作。如果要修改 next 的值,则需要复制/克隆 currentBag。

于 2010-04-09T13:37:03.040 回答