Skip to content

Instantly share code, notes, and snippets.

@DavidMah
Created April 3, 2012 04:41
Show Gist options
  • Save DavidMah/2289324 to your computer and use it in GitHub Desktop.
Save DavidMah/2289324 to your computer and use it in GitHub Desktop.
String Transformations
# string_transform
# Usage:
# ruby string_transform.rb <target string>
#
# The hello world of genetic algorithms creates
# a random string and mutates it until it becomes
# the target string
def get_worth(item, target)
sum = 0
item.size.times do |i|
sum += (item[i].ord - target[i].ord).abs
end
sum
end
def mutate(item)
index = rand(item.size)
new = item.split("")
new[index] = (rand(6) - 3 + new[index].ord).chr
new[index] = (rand(6) - 3 + new[index].ord).chr
new.join("")
end
def generate_initial(size)
item = ""
size.times do
item += (rand(26) + 'a'.ord).chr
end
item
end
target = ARGV[0]
current = generate_initial(target.size)
puts current
until get_worth(current, target) == 0
new = mutate(current)
new_worth = get_worth(new, target)
curr_worth = get_worth(current, target)
current = (curr_worth < new_worth ? current : new)
puts "#{current}: #{curr_worth}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment