forked from stinaq/WEASEL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoffee-script.coffee
45 lines (37 loc) · 1.14 KB
/
coffee-script.coffee
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
MUTATION_RATE = 0.04
LITTER_SIZE = 100
GENE_POOL = "abcdefghijklmnopqrstuvwxyz ".split ''
UBER_WEASEL = "methinks it is like a weasel"
randomGene = () -> GENE_POOL[Math.floor(Math.random() * GENE_POOL.length)]
class Weasel
constructor: (@genes) ->
@fitness = 0
calculateFitness: () ->
@fitness = (@genes.filter (e, i) -> UBER_WEASEL[i] is e).length
mutate: () ->
@genes = for letter in @genes
if (Math.random() < MUTATION_RATE) then randomGene()
else letter
@calculateFitness();
return this;
procreate: () ->
num = 0
while num++ < LITTER_SIZE
new Weasel(@genes).mutate()
evolution = (nextWeasel, count) ->
if nextWeasel.fitness is UBER_WEASEL.length
console.log "Uber weasel found"
else
litter = nextWeasel.procreate()
.sort((w1, w2) ->
if w1.fitness < w2.fitness then 1
else if w1.fitness > w2.fitness then -1
else 0)
bestWeasel = litter[0]
console.log(bestWeasel.fitness, bestWeasel.genes.join(''), count)
evolution bestWeasel, ++count
main = () ->
startWeasel = new Weasel(for letter in UBER_WEASEL
randomGene())
evolution(startWeasel, 0)
main()