Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 92 lines (70 sloc) 2.309 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
<html>
<head>
<title>Travelling Salesman Problem Sample</title>
<script src="../../lib/simplega.js" language="javascript"></script>
<script src="../tsp/tsp.js" language="javascript"></script>
</head>
<body>
<h1>Travelling Salesman Problem Sample</h1>

<input type="button" value="Relaunch" onclick="relaunch()">

<canvas id="canvas" width="600" height="500">
</canvas>

<script language="javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

function drawPoints()
{
    context.clearRect(0, 0, canvas.width, canvas.height);
    for (var k = 0; k < 5; k++)
        for (var j = 0; j < 4; j++) {
            context.beginPath();
            context.arc(50 + 100 * k, 50 + 100 * j, 10, 0, Math.PI * 2, true);
            context.closePath();
            context.fill();
        }
}

function drawValues(points, values)
{
    context.beginPath();
    
    var l = values.length;
    var point = points[values[0]];
    
    context.moveTo(50 + 100 * point.x, 50 + 100 * point.y);
    
    for (var k = 1; k < l; k++) {
        point = points[values[k]];
        context.lineTo(50 + 100 * point.x, 50 + 100 * point.y);
    }
    
    context.closePath();
    context.stroke();
}

var points = tsp.createPointRectangle(5, 4);
var maxlength = 5 * 4 * (5*5 + 4*4);

drawPoints();

var engine = new simplega.Engine();

var population = tsp.createPopulation(10000, points, maxlength);

engine.setMutators([new tsp.Mutator()]);

var bestvalue = 0;
var bestpath;

setTimeout(doStep, 10);

function doStep() {
    engine.setPopulation(population);
    population = engine.nextPopulation();
    var newbestvalue = simplega.getBestValue(population);
    
    if (newbestvalue >= bestvalue) {
        bestvalue = newbestvalue;
        var l = population.length;
        for (var k = 0; k < l; k++)
            if (population[k].evaluate() == newbestvalue) {
                drawPoints();
                drawValues(points, population[k].getValues());
            }
    }
    
    setTimeout(doStep, 10);
}

function relaunch() {
    var newpopulation = tsp.createPopulation(5000, points, maxlength);
        
    bestvalue = 0;
    population = newpopulation;
}

</script>
</body>
</html>
Something went wrong with that request. Please try again.