Guest User

Untitled

a guest
Jun 22nd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. TARGET = "Hello, world!"
  2.  
  3. class Array
  4. def pos_of_min
  5. min = 999999999999999
  6. pos = nil
  7. self.each_with_index do |a, i|
  8. if a < min
  9. pos = i
  10. min = a
  11. end
  12. end
  13. pos
  14. end
  15. end
  16.  
  17. def random_string
  18. (1..TARGET.size).collect {|x| 32 + rand(94) }
  19. end
  20.  
  21. def distance(chromosome)
  22. chromosome.zip(TARGET.unpack("c*")).inject(0) {|sum, a| sum += (a[1]-a[0]) ** 2}
  23. end
  24.  
  25. def mutate(chromosome)
  26. mutated = []
  27. chromosome.each_with_index do |a, i|
  28. mutated << if (a-TARGET[i]).abs > 0
  29. a + rand(7) - 3
  30. else
  31. a
  32. end
  33. end
  34. mutated
  35. end
  36.  
  37. def iterate(chromosome)
  38. candidates = 100.times.collect {mutate(chromosome)}
  39. scores = candidates.collect {|c| distance(c)}
  40. candidates[scores.pos_of_min]
  41. end
  42.  
  43. candidate = random_string
  44. puts "starting with: " + candidate.pack("c*")
  45. 50.times do |i|
  46. candidate = iterate(candidate)
  47. puts sprintf("%03d ", i+1) + candidate.pack("c*")
  48. end
Add Comment
Please, Sign In to add comment