Skip to content

Instantly share code, notes, and snippets.

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