85 lines
1.4 KiB
Plaintext
85 lines
1.4 KiB
Plaintext
import Nanoquery.Util
|
|
|
|
target = "METHINKS IT IS LIKE A WEASEL"
|
|
tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
|
|
copies = 30
|
|
chance = 0.09
|
|
rand = new(Random)
|
|
|
|
// returns a random string of the specified length
|
|
def rand_string(length)
|
|
global tbl
|
|
global rand
|
|
|
|
ret = ""
|
|
|
|
for i in range(1, length)
|
|
ret += tbl[rand.getInt(len(tbl))]
|
|
end
|
|
|
|
return ret
|
|
end
|
|
|
|
// gets the fitness of a given string
|
|
def fitness(string)
|
|
global target
|
|
fit = 0
|
|
|
|
for i in range(0, len(string) - 1)
|
|
if string[i] != target[i]
|
|
fit -= 1
|
|
end
|
|
end
|
|
|
|
return fit
|
|
end
|
|
|
|
// mutates the specified string with a chance of 0.09 by default
|
|
def mutate(string)
|
|
global chance
|
|
global rand
|
|
global tbl
|
|
mutated = string
|
|
|
|
for i in range(0, len(mutated) - 1)
|
|
if rand.getFloat() <= chance
|
|
mutated[i] = tbl[rand.getInt(len(tbl))]
|
|
end
|
|
end
|
|
|
|
return mutated
|
|
end
|
|
|
|
// a function to find the index of the string with the best fitness
|
|
def most_fit(strlist)
|
|
global target
|
|
|
|
best_score = -(len(target) + 1)
|
|
best_index = 0
|
|
|
|
for j in range(0, len(strlist) - 1)
|
|
fit = fitness(strlist[j])
|
|
if fit > best_score
|
|
best_index = j
|
|
best_score = fit
|
|
end
|
|
end
|
|
|
|
return {best_index, best_score}
|
|
end
|
|
|
|
parent = rand_string(len(target)); iter = 1
|
|
while parent != target
|
|
children = {}
|
|
|
|
for i in range(1, 30)
|
|
children.append(mutate(parent))
|
|
end
|
|
|
|
fit = most_fit(children)
|
|
parent = children[fit[0]]
|
|
print format("iter %d, score %d: %s\n", iter, fit[1], parent)
|
|
|
|
iter += 1
|
|
end
|