Skip to content

Commit

Permalink
updated simple example. added examples to package.json
Browse files Browse the repository at this point in the history
  • Loading branch information
literalsands committed Dec 15, 2017
1 parent 438fd61 commit d803a39
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
18 changes: 12 additions & 6 deletions example.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Population } from "./src/Population";
import { Individual } from "./src/Individual";
import { arity, choose } from "./src/PhenotypeHelpers";

let target = "It works!";
let population = new Population({
Expand All @@ -14,26 +15,31 @@ let population = new Population({
// Let the individuals choose their own mutation rate on initialization.
//rate: g => g
// We're making it a little easier to hit lower numbers.
rate: g => Math.tan(Math.PI / 4 * g)
//rate: g => Math.tan(Math.PI / 4 * g)
rate: g => (g * 0.06) + 0.02
}
}
],
value: function(a, b, c, d, e, f, g, h, i) {
// The arity function returns a function of a given length.
// That length is used to populate the genome.
string: arity(target.length, function() {
// Encode each gene into a valid character code.
var codes = Array.from(arguments).map(arg => {
return 32 + Math.floor(arg * (126 - 32));
});
// Convert the character codes into a string.
var string = String.fromCharCode(...codes);
return string;
}
})
}
}),
individuals: 50
individuals: 25
});

Population.Fitness["fitness"] = individual => {
// Give the individual an error point every time they don't match the target string.
return Array.from(target).reduce(
(n, v, i) => (v === individual.traits.value[i] ? n : n + 1),
(n, v, i) => (v === individual.traits.string[i] ? n : n + 1),
0
);
};
Expand All @@ -50,7 +56,7 @@ for (let i = 0; i < 500; i++) {
console.log(
sorted
.map(i => Population.Fitness.fitness(population.individuals[i]))
.join("")
.join(""), population.individuals[mostFit[0]].traits.string
);
// Crossover all the individuals with the most fit.
population.operation("crossoverAndReplace", [true, mostFit]);
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
"compile": "babel -d dist/ src/",
"prepublishOnly": "npm run compile",
"test": "mocha --compilers js:babel-core/register",
"example": "babel-node example.js",
"example:encode-word": "babel-node example.js",
"example:tic-tac-toe": "babel-node example-tictactoe.js",
"test:tap": "npm run test -- --reporter=TAP",
"test:examples": "mocha --compilers js:babel-core/register --require jsdoctest src/index.js",
"docs:generate": "node_modules/.bin/jsdoc -c jsdoc.json"
Expand Down

0 comments on commit d803a39

Please sign in to comment.