I translated the implementation in Chapter 1 (without mutation) for Ruby and get surprised that it’s find a solution much faster than the Elixir implementation.
The Ruby implementation finds the solution in about 10 seconds, while the Elixir one takes about 1 minute. I get a bit surprised by this result and couldn’t think of an explanation for this difference.
I’m sharing my Ruby implementation for anyone curious to explain this difference:
#!/usr/bin/env ruby
population =
Array.new(100) do
Array.new(1000) { [0, 1].sample }
end
def evaluate(population)
population.sort_by(&:sum).reverse
end
def selection(population)
population.each_slice(2)
end
def crossover(population)
population.reduce([]) do |offspring, parents|
cx_point = cut = rand(1...parents[0].length)
child1 = parents[0][0...cx_point] + parents[1][cx_point..-1]
child2 = parents[1][0...cx_point] + parents[0][cx_point..-1]
offspring << child1 << child2
end
end
def algorithm(population)
loop do
best = population.max_by(&:sum)
print "Current Best: #{best.sum}\r"
break best if best.sum == 1000
population = evaluate(population)
population = selection(population)
population = crossover(population)
end
end
solution = algorithm(population)
puts "\nAnswer is\n"
puts solution.inspect