-
-
Save havenwood/46f6c0ed884e0f961cc3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Weazel | |
CHARS = [*'A'..'Z', ' '] | |
def initialize target | |
@target = target | |
@best = Array.new(28) { CHARS.sample }.join | |
end | |
def call | |
0.upto Float::INFINITY do |n| | |
puts "#{n}:\t#{@best}" | |
break @best if @best == @target | |
@best = find_highest_scored(new_generation(@best)) | |
end | |
end | |
def score_for_string str | |
target_chars = @target.chars | |
score = 0 | |
str.each_char.with_index do |char, index| | |
score += 1 if char == target_chars[index] | |
end | |
score | |
end | |
def mutate_string string | |
string.each_char.map { |char| rand(100) > 95 ? CHARS.sample : char }.join | |
end | |
def new_generation seed_str | |
100.times.map { mutate_string(seed_str) } | |
end | |
def find_highest_scored generation | |
generation.max_by { |str| score_for_string(str) } | |
end | |
end | |
Weazel.new('METHINKS IT IS LIKE A WEASEL').call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment