JSFiddle - React, Tailwind, and code Playground
by joe chan
JavaScript
// agent (pos, name)
// e.g., agent[0] (2, 'a')
// five agents, find neighbor for all agents
function Agent (pos, name) {
this.pos = pos;
this.name = name;
this.nbhd = []; // array for neighborhood
}
Agent.prototype = {
emptyNbdd: function() {
this.nbhd = [];
},
cohesion: function() {
// set pos as the average of my nbhd.pos
},
print: function() {
console.log ('name: ' + this.name);
// print all my neighbors
console.log ('my nbhd:')
for (var i = 0; i < this.nbhd.length; i++)
console.log (' ' + this.nbhd[i].name);
}
}
function computeNbhd() {
var n = agents.length; // number of agents
var R = 10;
// test it with n = 5
for (var i = 0; i < n-1; i++) {
for (var j = i+1; j < n; j++) {
if (Math.abs(agents[i].pos - agents[j].pos) < R) {
agents[i].nbhd.push (agents[j]);
agents[j].nbhd.push (agents[i]);
}
}
}
}
var agents = [];
agents.push (new Agent(1,'a'));
agents.push (new Agent(3,'b'));
computeNbhd();
for (var i = 0; i < agents.length; i++) {
agents[i].print();
}