开发者

Java: Local search for a TSP error

I'm coding a simple local search algorithms for TSP in java. Here's the method:

public Permutation localSearch(Permutation best, int maxnoimprov) {
    int count = 0 ;
    Permutation candidate;
    do {
        candidate = stochastic_2_opt(best);
        count = (candidate.getLength() < best.getLength()) ? 0 : count+1;
        if (candidate.getLength() < best.getLength()) {
            best=candidate;
        }
        System.out.print("Candidate "); candidate.showPermutation(); System.out.println(" Current best: "+best.getLength());
    } while (count<maxnoimprov);
    return best;
}

The problem is that the if-statement is always true,so when running the method the output looks like this:

....3, 34, 43, 32, }LENGTH: 30464.0 Current best: 30464.0

....14, 37, 24, 49, }LENGTH: 31499.0 Current best: 31499.0

....8, 4, 20, 42, }LENGTH: 30710.0 Current best: 30710.0

....23, 33, 12, 6, }LENGTH: 29321.0 Current best: 29321.0

....11, 32, 28, 15, }LENGTH: 30545.0 Current best: 30545.0 ..........................................................

As you开发者_运维知识库 can see the "best" is always replaced by the "candidate" while it should not.

My code seems fine to me but something is obviously wrong.

NOTES:

1) I've checked the stochastic_2_opt() method and it's ok.

2) The getLength() method returns double values so i thought that could be a trap and i used Double.compare but even then didn't work.

3) I also notice that when writing the if-condition as (candidate.getLength() < best.getLength()) it's also always true.

Can you help me find where the mistake is?


I suspect the Permutation member variable that's holding the length is a static variable; that could explain the results perfectly. Then when stochastic_2_opt() creates a candidate, it inadvertently sets the length of best, too. Your belief that the if is always true is a red herring, in that case; the if would evaluate to false, but you'd still get the same result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜