Class: Centroid

Inherits:
Object show all
Defined in:
lib/centroid.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(position) ⇒ Centroid

Returns a new instance of Centroid.



32
33
34
# File 'lib/centroid.rb', line 32

def initialize(position)
  @position = position
end

Instance Attribute Details

#positionObject

Returns the value of attribute position.



30
31
32
# File 'lib/centroid.rb', line 30

def position
  @position
end

Class Method Details

.create_centroids(amount, nodes) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/centroid.rb', line 4

def create_centroids(amount, nodes)
  ranges = create_ranges(nodes, nodes[0].position.size)
  (1..amount).map do
    position = ranges.inject([]) do |array, range|
      array << rand_between(range[0], range[1])
    end
    new(position)
  end
end

Instance Method Details

#reposition(nodes) ⇒ Object

Finds the average distance of all the nodes assigned to the centroid and then moves the centroid to that position



38
39
40
41
42
43
44
45
46
47
# File 'lib/centroid.rb', line 38

def reposition(nodes)
  return if nodes.empty?
  averages = [0.0] * nodes[0].position.size
  nodes.each do |node|
    node.position.each_with_index do |position, index|
      averages[index] += position
    end
  end
  @position = averages.map {|x| x / nodes.size}
end