Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- TARGET = "Hello, world!"
- class Array
- def pos_of_min
- min = 999999999999999
- pos = nil
- self.each_with_index do |a, i|
- if a < min
- pos = i
- min = a
- end
- end
- pos
- end
- end
- def random_string
- (1..TARGET.size).collect {|x| 32 + rand(94) }
- end
- def distance(chromosome)
- chromosome.zip(TARGET.unpack("c*")).inject(0) {|sum, a| sum += (a[1]-a[0]) ** 2}
- end
- def mutate(chromosome)
- mutated = []
- chromosome.each_with_index do |a, i|
- mutated << if (a-TARGET[i]).abs > 0
- a + rand(7) - 3
- else
- a
- end
- end
- mutated
- end
- def iterate(chromosome)
- candidates = 100.times.collect {mutate(chromosome)}
- scores = candidates.collect {|c| distance(c)}
- candidates[scores.pos_of_min]
- end
- candidate = random_string
- puts "starting with: " + candidate.pack("c*")
- 50.times do |i|
- candidate = iterate(candidate)
- puts sprintf("%03d ", i+1) + candidate.pack("c*")
- end
Add Comment
Please, Sign In to add comment