Class: Cgl::Neighbors

Inherits:
Object
  • Object
show all
Defined in:
lib/cgl/neighbors.rb

Class Method Summary collapse

Class Method Details

.neighbors(agent, all_agents, height, width = height) ⇒ Object

given the index of an agent and the full grid, return an array with the values of the 8 neighboring agents assume periodic boundary conditions (wrap) all indexing is 0 based, so a 3 x 4 grid has these indexes:

0     1   2   3
4     5   6   7
8     9  10  11


11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/cgl/neighbors.rb', line 11

def self.neighbors(agent, all_agents, height, width = height)
  neighbors = Array.new
  row = agent/width
  column = agent%width
  neighbors.push all_agents[(row*width)+(column+1)%width]
  neighbors.push all_agents[((row+1)%height)*width+(column+1)%width]
  neighbors.push all_agents[((row+1)%height)*width+(column)]
  neighbors.push all_agents[((row+1)%height)*width+(column-1)%width]
  neighbors.push all_agents[row*width+(column-1)%width]
  neighbors.push all_agents[(row-1)*width+(column-1)%width]
  neighbors.push all_agents[(row-1)*width+(column)]
  neighbors.push all_agents[(row-1)*width+(column+1)%width]
  neighbors
end