Skip to content

Instantly share code, notes, and snippets.

@jlindsey
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jlindsey/94b0ec5a5df6832e494a to your computer and use it in GitHub Desktop.
Save jlindsey/94b0ec5a5df6832e494a to your computer and use it in GitHub Desktop.
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