Created
July 13, 2017 02:10
-
-
Save Tombert/8760ad12505d2c3541fc322b058d5bdc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
genomeTypes = | |
Dict( | |
[0,0,0,1] => "1", | |
[0,0,1,0] => "2", | |
[0,0,1,1] => "3", | |
[0,1,0,0] => "4", | |
[0,1,0,1] => "5", | |
[0,1,1,0] => "6", | |
[0,1,1,1] => "7", | |
[1,0,0,0] => "8", | |
[1,0,0,1] => "9", | |
[1,0,1,0] => "+", | |
[1,0,1,1] => "-", | |
[1,1,0,0] => "13", | |
[1,1,0,1] => "*", | |
[1,1,1,0] => "10", | |
[1,1,1,1] => "11", | |
[0,0,0,0] => "/" | |
) | |
operatorDict = | |
Dict( | |
"*" => ((x, y) -> x * y), | |
"+" => ((x, y) -> x + y), | |
"/" => ((x, y) -> x / y), | |
"-" => ((x, y) -> x - y) | |
) | |
function momOrDadGenome(mom, dad, index) | |
coinflip = rand(0:1) | |
if coinflip == 0 mom[index] else dad[index] end | |
end | |
function dnaShuffle(mom, dad, genomeSize) | |
genomeMom, _ = mom | |
genomeDad, _ = dad | |
([momOrDadGenome(genomeMom,genomeDad,i) for i = 1:genomeSize],0) | |
end | |
function mutate(parent, mutrate) | |
(genome,_) = parent | |
numToMutate = Int64(ceil(mutrate * length(genome))) | |
mutateIndexes = rand(1:length(genome), numToMutate) | |
for i in mutateIndexes | |
genome[i] = rand(0:1, 4) | |
end | |
genome | |
end | |
function breed(mom, dad, littersize, genomeSize) | |
mutrate = .5 | |
[(mutate(dnaShuffle(mom, dad, genomeSize), mutrate), 0) for j = 1:genomeSize for i = 1:littersize] | |
end | |
function score(baby, targetNum) | |
(genome, _) = baby | |
currentOperator = Nullable() | |
numValue = -1 | |
oldNumValue = -1 | |
sum = 0 | |
for i in genome | |
value = genomeTypes[i] | |
if haskey(operatorDict, value) && currentOperator != "" | |
currentOperator = Nullable(operatorDict[value]) | |
else | |
numValue = parse(value) | |
end | |
if numValue != -1 && !isnull(currentOperator) | |
cop = get(currentOperator) | |
sum = cop(oldNumValue, numValue) | |
# println(targetNum) | |
currentOperator = Nullable() | |
oldNumValue = sum | |
end | |
end | |
#println(abs(targetNum - sum)) | |
(genome, abs(targetNum - sum)) | |
end | |
function fst(x) | |
(y,_) = x | |
y | |
end | |
function snd(x) | |
z,y = x | |
println(x) | |
y | |
end | |
function main() | |
iterations = 1000 | |
mom = ([rand(0:1, 4) for i = 1:9],0) | |
dad = ([rand(0:1, 4) for i = 1:9],0) | |
for i = 1:iterations | |
litter = breed(mom, dad, 10, 9) | |
newLitter = [score(i, 23) for i in litter] | |
sortedLitter = sort(newLitter, by = x -> x[2] , rev = false) | |
mom = sortedLitter[1] | |
dad = sortedLitter[2] | |
println("Mom score: $(mom[2]), genome: $(mom[1])") | |
end | |
end | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment