Search
 
SCRIPT & CODE EXAMPLE
 

LUA

lua genetic algorithm

local target = "METHINKS IT IS LIKE A WEASEL"
local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
local c, p = 100, 0.06
 
local function fitness(s)
	local score = #target
	for i = 1,#target do
		if s:sub(i,i) == target:sub(i,i) then score = score - 1 end
	end
	return score
end
 
local function mutate(s, rate)
	local result, idx = ""
	for i = 1,#s do
		if math.random() < rate then
			idx = math.random(#alphabet)
			result = result .. alphabet:sub(idx,idx)
		else
			result = result .. s:sub(i,i)
		end
	end
	return result, fitness(result)
end
 
local function randomString(len)
	local result, idx = ""
	for i = 1,len do
		idx = math.random(#alphabet)
		result = result .. alphabet:sub(idx,idx)
	end
	return result
end
 
local function printStep(step, s, fit)
	print(string.format("%04d: ", step) .. s .. " [" .. fit .."]")
end
 
math.randomseed(os.time())
local parent = randomString(#target)
printStep(0, parent, fitness(parent))
 
local step = 0
while parent ~= target do
	local bestFitness, bestChild, child, fitness = #target + 1
	for i = 1,c do
		child, fitness = mutate(parent, p)
		if fitness < bestFitness then bestFitness, bestChild = fitness, child end
	end
	parent, step = bestChild, step + 1
	printStep(step, parent, bestFitness)
end
Comment

PREVIOUS NEXT
Code Example
Lua :: roblox studio rain 
Lua :: Tool script example for lua 
Lua :: wait for player character roblox 
Lua :: shift to sprint 
Lua :: delete part on touch roblox 
Lua :: lua string to binary 
Lua :: lua unpack 5.4 
Lua :: lua table functions 
Lua :: random number lua 
Lua :: 1.2 / 1.6 
Lua :: how do i use the errors module luaassist 
Lua :: lua how to default value if nil 
Lua :: lua table of alphabet 
Matlab :: matlab measure time 
Matlab :: matlab symbolic variables 
Matlab :: matlab if bigger than 
Matlab :: matlab text subscript 
Basic :: hello world in basic 
Basic :: basic murmur hash function 
Elixir :: elixir replace string 
Elixir :: elixir enum chunk_every 
Scala :: else if scala 
Scala :: How to have scalable images using image view xamarin XML 
Actionscript :: mount_osxfuse : Input/output error 
Excel :: excel or function 
Perl :: Perl list files and folders in a directory 
Pascal :: wait in pascal 
Powershell :: Auto-open DevTools on every new tab For powershell on Windows 
Abap :: abap shortcut comments 
Assembly :: vba hello world 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =