| Path: | lib/charlie/list/list_genotype.rb |
| Last Update: | Thu Jan 24 23:51:02 +0100 2008 |
This file defines several different genotype (aka genome, chromosomes) classes. Inherit from one of these classes and define a fitness function to use them.
# File lib/charlie/list/list_genotype.rb, line 14
14: def initialize
15: @genes = Array.new(size){ rand * (@@range.end - @@range.begin) + @@range.begin }
16: end
# File lib/charlie/list/list_genotype.rb, line 51
51: def initialize
52: @genes = Array.new(size){ elements.at_rand }
53: end
# File lib/charlie/list/list_genotype.rb, line 31
31: def initialize
32: @genes = Array.new(size){ rand(2) }
33: end
Genotype of n bits. Individuals are initialized as an array of n random bits.
# File lib/charlie/list/list_genotype.rb, line 26
26: def BitStringGenotype(n)
27: Class.new(Genotype) {
28: [self,metaclass].each{|c| c.class_eval{ # include both in class and metaclass
29: define_method(:size){ n }
30: }}
31: def initialize
32: @genes = Array.new(size){ rand(2) }
33: end
34: def to_s
35: @genes.map(&:to_s).join
36: end
37: use ListMutator(:expected_n,:flip), SinglePointCrossover.dup
38: }
39: end
Genotype of n floats in the range range. Individuals are initialized as an array of n random numbers in this range. Note that mutations may cross range min/max.
# File lib/charlie/list/list_genotype.rb, line 8
8: def FloatListGenotype(n,range=0..1)
9: Class.new(Genotype) {
10: @@range = range
11: [self,metaclass].each{|c| c.class_eval{ # include both in class and metaclass
12: define_method(:size){ n }
13: }}
14: def initialize
15: @genes = Array.new(size){ rand * (@@range.end - @@range.begin) + @@range.begin }
16: end
17: def to_s
18: @genes.inspect
19: end
20: use ListMutator(), SinglePointCrossover.dup
21: }
22: end
Genotype of n elements (not necessarily chars). Individuals are initialized as an array of n elements, each randomly chosen from the elements array.
# File lib/charlie/list/list_genotype.rb, line 43
43: def StringGenotype(n,elements)
44: elements = elements.chars if elements.is_a? String # string to array of chars
45: elements = elements.to_a
46: Class.new(Genotype) {
47: [self,metaclass].each{|c| c.class_eval{ # include both in class and metaclass
48: define_method(:size){ n }
49: define_method(:elements){ elements }
50: }}
51: def initialize
52: @genes = Array.new(size){ elements.at_rand }
53: end
54: def to_s
55: @genes.map(&:to_s).join
56: end
57: use ListMutator(:expected_n[2],:replace[*elements]), SinglePointCrossover.dup
58: }
59: end