public
Created

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
class Chromosome
attr_accessor :bitstring
 
def fitness
@fitness = @bitstring ^ 0b0101
end
 
def self.random_chromosomes(length, number)
return Array.new(length) { Chromosome.new(length) }
end
 
def initialize(length, bitstring = nil)
if bitstring
@bitstring = bitstring
else
@bitstring = rand(2**length+1).to_s(2).rjust(length, '0')
end
fitness
end
 
def self.fitnesses(chrs)
chrs.each do |c|
c.fitness
end
end
 
def self.total_fitness(chrs)
total = 0
chrs.each do |c|
total += chrs.fitness
end
return total
end
 
def self.roulette(chrs)
roulette=[]
chrs.each { |chr|
chr.fitness.times { roulette << chr }
}
roulette.sample
end
 
def self.produceNew(chrs)
 
newchrs = []
chrs.each do |c|
newchrs.push(roulette(chrs))
end
fitnesses(newchrs)
 
return newchrs
end
 
def cross(mate)
cs = crossover_site = rand(@bitstring.length-1)+1
mate.bitstring[cs..-1], @bitstring[cs..-1] = @bitstring[cs..-1], mate.bitstring[cs..-1]
end
 
def self.do_crossings(chrs, mates)
i = 0
completed = []
 
#not very idiomatic, but, the i variable is important
while i < chrs.length
 
#due to the symmetric nature of the data structure we're using
if completed.include? i
i += 1
next
end
chrs[i].cross(chrs[mates[i]])
 
completed.push(mates[i])
i += 1
end
return chrs
 
end
def self.get_mates(chrs)
i = 0
res = {}
while i < chrs.length
res[i] = i+1
res[i+1] = i
i += 2
end
res
end
end
 
i = 0
 
chrs = Chromosome.random_chromosomes(4, 4)
 
100.times do
chrs = Chromosome.produce_new(chrs)
mates = Chromosome.get_mates(chrs)
chrs = Chromosome.do_crossings(chrs, mates)
puts chrs.inspect
end
 
puts chrs.inspect

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.