Last active
August 29, 2015 14:02
-
-
Save jlindsey/94b0ec5a5df6832e494a 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
TARGET = %{METHINKS IT IS LIKE A WEASEL} | |
CHARS = (('A'..'Z').to_a << ' ') | |
INITIAL_SEED_STR = '' | |
28.times { INITIAL_SEED_STR << CHARS.shuffle.first } | |
def score_for_string str | |
score = 0 | |
target_chars = TARGET.chars | |
str.chars.each_with_index do |char, i| | |
score += 1 if char == target_chars[i] | |
end | |
return score | |
end | |
def mutate_string! string | |
chars = [] | |
string.chars.each do |char| | |
if rand(100) > 95 | |
chars << CHARS.shuffle.first | |
else | |
chars << char | |
end | |
end | |
return chars.join | |
end | |
def new_generation seed_str | |
generation = [] | |
100.times { generation << mutate_string!(seed_str) } | |
return generation | |
end | |
def find_highest_scored generation | |
return generation.sort_by { |str| score_for_string str }.last | |
end | |
i = 0 | |
best = INITIAL_SEED_STR | |
loop do | |
puts "#{i}:\t#{best}" | |
i += 1 | |
break if best == TARGET | |
best = find_highest_scored(new_generation(best)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment