xxxxxxxxxx
106
class Ant {
constructor(startPoint, points) {
this.pos = startPoint
this.points = points;
this.visited = [startPoint];
}
calcDist() {
let acc = 0;
for (let i = 1; i < this.visited.length; i++) {
acc += this.visited[i - 1].dist(this.visited[i]);
}
return acc;
}
getPheromones() {
let res = [];
for (let i = 1; i < this.visited.length; i++) {
let p1 = this.visited[i - 1]
let p2 = this.visited[i]
let d = p1.dist(p2)
res.push({
p1,
p2,
amount: pow(0.2 / d, sliderDistPow.value())
});
}
return res;
}
drawPheromone(phero) {
for (let {
p1,
p2,
amount
} of phero) {
stroke(pow(amount, sliderPheroPow.value()) * 255)
line(p1.x * width, p1.y * height, p2.x * width, p2.y * height)
}
}
draw() {
for (let i = 0; i < this.visited.length; i++) {
noStroke();
let p = this.visited[i];
//fill(0, 255, 0);
//ellipse(p.x * width, p.y * height, 10, 10);
stroke(255)
if (i + 1 < this.visited.length) {
let next = this.visited[i + 1];
line(p.x * width, p.y * height, next.x * width, next.y * height);
}
}
noStroke();
fill(255, 0, 0);
ellipse(this.pos.x * width, this.pos.y * height, 8, 8);
}
generatePath(pheromones) {
this.visited = [this.pos];
while (this.visitNext(pheromones)) {}
}
visitNext(pheromones) {
//print(1)
while (this.visited.length < this.points.length) {
let avail = this.points.filter(p => !this.visited.includes(p));
let weighted = avail
.map(a => {
let phero = 1;
let p = getPheroFromArray(pheromones, a.p1, a.p2)
if (p) {
print(p.amount)
phero = p.amount;
}
return {
ele: a,
chance: pow(0.2 / this.pos.dist(a), sliderDistPow.value()) * pow(phero, sliderPheroPow.value())
};
})
let next = selectRandomWeighted(weighted).ele;
this.pos = next;
this.visited.push(next);
return true;
}
this.pos = this.visited[0];
this.visited.push(this.visited[0]);
return false;
}
}
function selectRandomWeighted(elements) {
let sum = elements.reduce((acc, cur) => acc + cur.chance, 0);
let r = random(sum)
let acc = 0;
for (let ele of elements) {
acc += ele.chance;
if (acc > r) {
return ele;
}
}
}