forked from stinaq/WEASEL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnimrod.nim
58 lines (48 loc) · 1.42 KB
/
nimrod.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import math, times
const
UltraWeasel = "methinks it is like a weasel"
GenePool = "abcdefghijklmnopqrstuvwxyz "
LitterSize = 100
#MutationFactor = 0.04 # floating point randomness isnt supported on Windows
MutationFactor = 4
proc randomGene(): char =
return GenePool[math.random(GenePool.len)]
type
TWeasel = object of TObject
genes: string
score: int
method calculateScore(w: var TWeasel) =
w.score = 0
for i, g in w.genes:
if g == UltraWeasel[i]:
w.score += 1
method createChild(w: TWeasel): TWeasel =
result = TWeasel(genes: w.genes)
for i, g in result.genes:
if math.random(100) < MutationFactor:
result.genes[i] = randomGene()
result.calculateScore()
method createLitter(w: TWeasel): seq[TWeasel] =
result = @[]
for i in 1..LitterSize:
result.add(w.createChild())
proc newWeasel(): TWeasel =
var newGenes = ""
for i in 1..UltraWeasel.len:
newGenes.add($randomGene())
result = TWeasel(genes: newGenes)
result.calculateScore()
proc main(w: TWeasel, counter: int) =
echo(counter, "\t", w.score, "\t", w.genes)
if w.score == UltraWeasel.len:
return
let litter = w.createLitter()
var bestOfLitter = litter[0]
for i in 1..litter.len - 1:
if litter[i].score > bestOfLitter.score:
bestOfLitter = litter[i]
main(bestOfLitter, counter + 1)
math.randomize(cast[int](times.epochTime()))
echo("Gen\tScore\tGenes")
echo("===\t=====\t=====")
main(newWeasel(), 1)