Created
November 26, 2015 19:31
-
-
Save roobie/37e08651c52fb760df86 to your computer and use it in GitHub Desktop.
weasel with a Y combinator
This file contains hidden or 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
| (function () { | |
| "use strict"; | |
| const goal = "METHINKS IT IS LIKE A WEASEL"; | |
| const size = 100; | |
| const rate = 0.04; | |
| const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; | |
| var range = function (count) { | |
| return new Array(count).join(' ').split(' '); | |
| }; | |
| var randGene = function () { | |
| return alphabet[Math.floor(Math.random() * alphabet.length)]; | |
| }; | |
| var getScore = function (weasel) { | |
| return weasel.split('').reduce(function (out, next, i) { | |
| return out + Number(next === goal[i]); | |
| }, 0); | |
| }; | |
| var createChild = function (parent) { | |
| return parent.split('').map(function (c) { | |
| return Math.random() < rate ? randGene() : c; | |
| }).join(''); | |
| }; | |
| // Y combinator | |
| // see http://matt.might.net/articles/implementation-of-recursive-fixed-point-y-combinator-in-javascript-for-memoization/ | |
| var Y = function (F) { | |
| return (function (x) { | |
| return F(function (y) { | |
| return (x(x))(y) | |
| }); | |
| })(function (x) { | |
| return F(function (y) { | |
| return (x(x))(y) | |
| }); | |
| }); | |
| }; | |
| var algo = Y(function (step) { | |
| return function (acc) { | |
| var curState = acc.slice(-1)[0]; | |
| if (curState.bestWeasel === goal) { | |
| return acc; | |
| } | |
| var litter = range(size).map(function () { | |
| return createChild(curState.bestWeasel); | |
| }); | |
| var sorted = litter.sort(function (a, b) { | |
| return getScore(b) - getScore(a); | |
| }); | |
| var newBestWeasel = sorted[0]; | |
| return step(acc.concat({ | |
| bestWeasel: newBestWeasel, | |
| score: getScore(newBestWeasel), | |
| generation: curState.generation + 1 | |
| })); | |
| }; | |
| }); | |
| var initWeasel = range(goal.length).map(randGene).join(''); | |
| var initialState = [{ | |
| bestWeasel: initWeasel, | |
| score: getScore(initWeasel), | |
| generation: 0 | |
| }]; | |
| var result = algo(initialState); | |
| result.forEach(function (state) { | |
| console.log(state.generation, state.bestWeasel, state.score); | |
| }); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment