Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function table_print (tt, indent, done)
- done = done or {}
- indent = indent or 0
- if type(tt) == "table" then
- local sb = {}
- for key, value in pairs (tt) do
- table.insert(sb, string.rep (" ", indent)) -- indent it
- if type (value) == "table" and not done [value] then
- done [value] = true
- table.insert(sb, key .. " = {\n");
- table.insert(sb, table_print (value, indent + 2, done))
- table.insert(sb, string.rep (" ", indent)) -- indent it
- table.insert(sb, "}\n");
- elseif "number" == type(key) then
- table.insert(sb, string.format("\"%s\"\n", tostring(value)))
- else
- table.insert(sb, string.format(
- "%s = \"%s\"\n", tostring (key), tostring(value)))
- end
- end
- return table.concat(sb)
- else
- return tt .. "\n"
- end
- end
- function to_string( tbl )
- if "nil" == type( tbl ) then
- return tostring(nil)
- elseif "table" == type( tbl ) then
- return table_print(tbl)
- elseif "string" == type( tbl ) then
- return tbl
- else
- return tostring(tbl)
- end
- end
- function create_population(pop_size, gene_len)
- local population = {}
- for i = 1, pop_size do
- local individual = {}
- for j = 1, gene_len do
- individual[j] = math.random(0, 1)
- end
- population[i] = individual
- end
- return population
- end
- function evaluate_fitness(pop)
- local fitness = {}
- for i, ind in ipairs(pop) do
- local sum = 0
- for j, gene in ipairs(ind) do
- sum = sum + gene
- end
- fitness[i] = sum
- end
- return fitness
- end
- function select_parents(pop, fit)
- local parents = {}
- for i = 1, #pop do
- local p1 = math.random(1, #pop)
- local p2 = math.random(1, #pop)
- if fit[p1] > fit[p2] then
- parents[i] = pop[p1]
- else
- parents[i] = pop[p2]
- end
- end
- return parents
- end
- function crossover(par, pop_size, gene_len)
- local offspring = {}
- for i = 1, pop_size, 2 do
- local p1 = par[i]
- local p2 = par[i+1]
- local o1 = {}
- local o2 = {}
- for j = 1, gene_len do
- if math.random(0, 1) == 0 then
- o1[j] = p1[j]
- o2[j] = p2[j]
- else
- o1[j] = p2[j]
- o2[j] = p1[j]
- end
- end
- offspring[i] = o1
- offspring[i+1] = o2
- end
- return offspring
- end
- function mutation(off, mut_rate, gene_len)
- for i, ind in ipairs(off) do
- for j = 1, gene_len do
- if math.random() < mut_rate then
- ind[j] = 1 - ind[j]
- end
- end
- end
- return off
- end
- function genetic_algorithm(pop_size, gene_len, mut_rate, generations)
- local pop = create_population(pop_size, gene_len)
- for i = 1, generations do
- local fit = evaluate_fitness(pop)
- local par = select_parents(pop, fit)
- local off = crossover(par, pop_size, gene_len)
- pop = mutation(off, mut_rate, gene_len)
- end
- return pop
- end
- result = genetic_algorithm(8, 4, 0.01, 100)
- print(to_string(result))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement