开发者

Problem Swapping Pairs Between 2 Arrays

I'm working on a mutation algorithm for a homework project and I'm stumped at why I'm getting duplicates in the set. I'm trying to find a solution for the travelling ant problem (find shortest path for food) problem using a genetic mutation heuristic:

private static ArrayList<Node> mutate(ArrayList<Node> mutator) {
    ArrayList<Node> mutant = new开发者_如何学C ArrayList<Node>(mutator);

    Collections.rotate(mutant, 1);
    //Collections.shuffle(mutant, r);

    for (int i = 0; i < mutant.size() - 1; i++) {
        double mutantCoupleDistance     = mutant.get(i).getDistanceToNext(mutant.get(i+1));
        double mutatorCoupleDistance    = mutator.get(i).getDistanceToNext(mutator.get(i+1));

        if (mutantCoupleDistance < mutatorCoupleDistance) {
            // If the mutant gene has worse "fitness" then we'll take the good gene
            // from the mutator.
            Node tmp = mutant.get(i);
            mutant.set(i, mutator.get(i));
            mutator.set(i, tmp);

            tmp = mutant.get(i+1);
            mutant.set(i+1, mutator.get(i+1));
            mutator.set(i+1, tmp);
        }
    }

    return 
        mutant;
}

The array that I'm passing into the method is 49999 elements. It is being used like in a way like so:

        long
            startTime = System.currentTimeMillis();

        do {
            nodeList = mutate(nodeList);
        } while (System.currentTimeMillis() - startTime < 500);

I do not get any duplicates when I remove the swapping code from my mutate algorithm which is understandable. However, I'm having trouble understanding why I'm getting duplicates in the mutated list.

The node list starts off with no duplicates. The code I'm using to report duplicates is the following code:

    HashSet<Node> set = new HashSet<Node>(nodeList);

    if(set.size() < nodeList.size()){
        System.out.println("duplicates found Set:" + set.size() + " vs. NodeList:" + nodeList.size());
    }

Thank you for any assistance.


What the code does now is rotate the copy by 1. Then at some points, you swap items from the copy and the original at the same index. Then after a swap, you have two equal elements next to each other. For example, a b c d and rotated copy d a b c:

abcd
 ▲
 swap here
 ▼
dabc

Gives

aacd
dbbc

Every swap will give a duplicate. The code rotates the array and makes duplicates.

From your comment it sounds like you're using Hill climbing for something close to the Traveling Salesman. But, if you want GA, you need a lot of ArrayList<Node> mutator or working paths, and randomly combine those into new ones.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜