Skip to content

Instantly share code, notes, and snippets.

@ken210
Created February 22, 2016 16:14
Show Gist options
  • Save ken210/f57ccb4feee8483104e9 to your computer and use it in GitHub Desktop.
Save ken210/f57ccb4feee8483104e9 to your computer and use it in GitHub Desktop.
/*
This code does the following:
1 - Start a new population of 50 "numbers" and a GOAL of 9999
2 - Select the two highest multiple of 3 available
3 - Create a new generation of numbers ranging between it's parents values, incresing a little
4 - Do that until reaches the GOAL
*/
var GOAL = 9999;
var SIZE = 50;
var MULTIPLE_OF = 3;
var INCREASE = MULTIPLE_OF;
function getRandom(minNum, maxNum) {
if (minNum == null) {
minNum = 0;
}
if (maxNum == null) {
throw new Error('getRandom was called without a maxNum');
}
return Math.floor(Math.random() * (maxNum - minNum)) + minNum;
}
function selectCouple(members) {
var sorted = members.filter(function (member) {
return member % MULTIPLE_OF === 0;
}).sort();
if (!sorted || sorted.length < 2) {
throw new Error('Extinction!')
}
return [sorted[sorted.length - 2], sorted[sorted.length - 1]];
}
function Pop () {
var member;
this.members = [];
console.log('Starting Population with these members:');
for (var i = 0; i < SIZE; i++) {
member = getRandom(null, GOAL);
this.members.push(member);
console.log(' - ' + member);
}
}
Pop.prototype.isDone = function (last) {
this.rounds = this.rounds || 1;
console.log('Round ' + this.rounds);
if (last >= GOAL) {
console.log('=========')
console.log('Done! In ' + this.rounds + ' rounds');
return true;
}
this.rounds++;
return false;
}
Pop.prototype.generate = function () {
var selectedMembers = selectCouple(this.members);
var first = selectedMembers[0];
var last = selectedMembers[1];
if (first === last) {
last = last + INCREASE;
}
if (this.isDone(last)) {
return;
}
var member;
this.members = [];
console.log('New generation for [' + first.toString() + ', ' + last.toString() + ']');
for (var i = 0; i < SIZE; i++) {
member = getRandom(first, last + INCREASE);
this.members.push(member);
console.log(' - ' + member);
}
this.generate();
}
var pop = new Pop();
pop.generate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment