Class: Wallace::Species::ArraySpecies

Inherits:
Wallace::Species show all
Defined in:
lib/species/array_species.rb

Overview

Array-based species model their members as arrays of set values.

Instance Attribute Summary

Attributes inherited from Wallace::Species

#id

Instance Method Summary collapse

Methods inherited from Wallace::Species

#finish!

Constructor Details

#initialize(opts = {}) ⇒ ArraySpecies

Constructs a new array-based species.

Parameters:

  • opts, hash of keyword options used by this method. -> id, the unique identifier for this species. -> length, the length constraints imposed on individuals of this species. -> values, the possible values of array elements (can be either a range or an array).



13
14
15
16
17
# File 'lib/species/array_species.rb', line 13

def initialize(opts = {})
  super(opts)
  @length = opts[:length]
  @values = opts[:values]
end

Instance Method Details

#spawn(opts = {}) ⇒ Object

Creates a new array-based individual using the set of values and length constraints of the species.

Parameters:

  • opts, hash of keyword options used by this method. -> random, the RNG to use when spawning individuals.



33
34
35
36
37
38
# File 'lib/species/array_species.rb', line 33

def spawn(opts = {})
  opts[:random] ||= Random.new
  size = @length.is_a?(Range) ? opts[:random].rand(@length) : @length
  data = Array.new(size) { @values.sample(opts) }
  return Wallace::Individual.new(self, data)
end

#valid?(individual) ⇒ Boolean

Check that a given individual meets the length constraints of the species.

Returns:

  • (Boolean)


20
21
22
23
24
25
# File 'lib/species/array_species.rb', line 20

def valid?(individual)
  return false unless super(individual)
  return true if @length.nil?
  return false if @length.is_a? Integer and individual.data.length != @length
  return false if @length.is_a? Range and (not @length.include? individual.data.length)
end