Skip to content

Instantly share code, notes, and snippets.

@oldmud0
Last active April 14, 2016 03:27
Show Gist options
  • Save oldmud0/7dc4cce7b9530fbb3ff6de38f0eabcc6 to your computer and use it in GitHub Desktop.
Save oldmud0/7dc4cce7b9530fbb3ff6de38f0eabcc6 to your computer and use it in GitHub Desktop.
/*
//Sample genetic-ish algorithm
Original:
[[0, 0
[0 .
.
. ]
0]]
Desired:
[[x1,
[ x2
... ]
x8]]
such that x1 + x2 + ... + x8 >= 10000
(Yes I know, 8 variables means 7 degrees of freedom, but this algorithm discounts that
and instead makes a nice pretty distribution)
*/
var arr = [0, 0, 0, 0, 0, 0, 0, 0];
for(var i = 0; i < arr.length; i++) {
arr[i] = [0, 0, 0, 0, 0, 0, 0, 0];
}
var generation = 0, instability = 2, population = 600, targetFitness = 10000;
function getFitness(tempArr) {
var fitness = 0;
for(var i = 0; i < tempArr.length; i++) {
fitness += tempArr[i][i];
}
return fitness;
}
function mutate(tempArr) {
for(var i = 0; i < tempArr.length; i++)
for(var j = 0; j < tempArr[i].length; j++)
tempArr[i][j] += Math.round(Math.random() * instability - instability/2);
}
function copyArr(tempArr) {
var newArr = tempArr.slice(0);
for(var i = 0; i < tempArr.length; i++) { //
newArr[i] = tempArr[i].slice(0);
}
return newArr;
}
var currFitness = 0;
while(currFitness < targetFitness) {
var bestFitness = 0, bestArr = arr, fit, tempArr;
for(var p = 0; p < population; p++) {
tempArr = copyArr(arr); //Duplicate array
mutate(tempArr);
fit = getFitness(tempArr);
if(fit > bestFitness) {
bestFitness = fit;
bestArr = tempArr;
}
}
arr = bestArr;
currFitness = bestFitness;
generation++;
if(generation % 1000 === 0)
console.log(generation + ": " + currFitness);
}
console.log(generation + ": " + currFitness);
console.log(arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment