HW04 class

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

Agent.prototype = {
	emptyNbdd: function() {
  	this.nbhd = [];
  },
  cohesion: function() {
  var total=0 , avg=0;
  	// set pos as the average of my nbhd.pos
    for(var i=0;i<this.nbhd.length;i++){
    	total+= this.nbhd[i].pos;
    }
    avg=total/i+1;
    this.newpos=avg;
  }, 
  print: function() {
  	console.log ('name: ' + this.name +' pos '  +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 = 5;
  
  // 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(8,'c'));
agents.push (new Agent(11,'d'));

computeNbhd();

for (var i = 0; i < agents.length; i++) {
	agents[i].cohesion();
}
for (var i = 0; i < agents.length; i++) {
	agents[i].print();
}
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();
}