Certainly! The "weasel program" or "Dawkins' weasel" is a simple evolutionary algorithm that demonstrates the power of cumulative selection. The program starts with a random string of characters and then, through a process of replication with mutation, evolves this string toward a target phrase. Below is a basic implementation of the "weasel program" in Lua 5.1, without using any libraries.
-- Parameters
local target = "METHINKS IT IS LIKE A WEASEL"
local charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
local mutationRate = 0.05 -- 5% mutation rate
local populationSize = 100
-- Function to generate a random string of the same length as the target
function randomString()
local result = ""
for i = 1, #target do
local randIndex = math.random(1, #charset)
result = result .. charset:sub(randIndex, randIndex)
end
return result
end
-- Function to mutate a string
function mutate(str)
local mutated = ""
for i = 1, #str do
if math.random() < mutationRate then
local randIndex = math.random(1, #charset)
mutated = mutated .. charset:sub(randIndex, randIndex)
else
mutated = mutated .. str:sub(i, i)
end
end
return mutated
end
-- Function to calculate the fitness of a string compared to the target
function fitness(str)
local score = 0
for i = 1, #str do
if str:sub(i, i) == target:sub(i, i) then
score = score + 1
end
end
return score
end
-- Main evolutionary loop
local generation = 0
local best = randomString()
local bestFitness = fitness(best)
math.randomseed(os.time())
while bestFitness < #target do
local newGeneration = {}
for i = 1, populationSize do
local offspring = mutate(best)
table.insert(newGeneration, offspring)
end
for i, candidate in ipairs(newGeneration) do
local candidateFitness = fitness(candidate)
if candidateFitness > bestFitness then
best = candidate
bestFitness = candidateFitness
end
end
generation = generation + 1
print("Generation " .. generation .. ": " .. best .. " (Fitness: " .. bestFitness .. ")")
end
print("Target reached in generation " .. generation)
This script defines a basic version of the "weasel program". It starts by generating a random string and evolves this string towards the predefined target, "METHINKS IT IS LIKE A WEASEL", through a process of replication and mutation. The program prints the best string of each generation along with its fitness, which is the number of characters that match the target string. The loop continues until the program evolves a string that exactly matches the target.
Remember to run this script, you'll need Lua 5.1 installed on your system. The program uses basic Lua functions and should work as expected, showing how the initial random string evolves over generations towards the target phrase.