JSFiddle - React, Tailwind, and code Playground

by Rebecca Chen

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
  this.newpos = 0;
}

Agent.prototype = {
	emptyNbd: function() {
  	this.nbhd = [];
  },
  cohesion: function() {
  	var sum = 0
		for (var i = 0; i < this.nbhd.length; i++) {
    	sum += this.nbhd[i].pos;
    }
    this.newpos = sum/this.nbhd.length;
  }, 
  print: function() {
  	console.log ('name: ' + this.name + ': '+ this.pos);
/*    // 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'));
agents.push (new Agent(5,'c'));

computeNbhd();

for (var i = 0; i < agents.length; i++) {
	agents[i].cohesion();
}
for (var i = 0; i < agents.length; i++) {
	agents[i].pos = agents[i].newpos;
}
for (var i = 0; i < agents.length; i++) {
	agents[i].print();
}