Skip to content

Instantly share code, notes, and snippets.

@scriptype
Created February 22, 2018 22:03
Show Gist options
  • Save scriptype/f02063b67e9236c58ba4e17c325ab9d3 to your computer and use it in GitHub Desktop.
Save scriptype/f02063b67e9236c58ba4e17c325ab9d3 to your computer and use it in GitHub Desktop.
Hello world example with genetic algorithm
(() => {
function nArray(n, mapperFn) {
return new Array(n).join(' ').split(' ').map(mapperFn)
}
function getRandomString(length) {
return nArray(length, e =>
String.fromCharCode(Math.round(Math.random() * 126))
).join('')
}
function mutate(previous) {
var length = previous.length
var randomIndex = Math.floor(Math.random() * length)
return previous
.slice(0, randomIndex)
.concat(getRandomString(1))
.concat(previous.slice(randomIndex + 1))
}
function selectiveBreed(candidates, ideal, amount) {
return candidates
.map(candidate => ({
distance: candidate.split('').reduce((distance, char, i) => (
distance += Math.abs(
ideal.charCodeAt(i) -
char.charCodeAt(0)
)
), 0),
original: candidate
}))
.sort((a, b) => a.distance - b.distance)
.slice(0, amount)
.map(a => a.original)
}
function iterate(seed, solution, limit) {
console.log(seed, limit)
if (seed === solution) {
return seed
}
if (limit-- > 0) {
var next = selectiveBreed(
nArray(100, e => mutate(seed)),
solution,
1
)[0]
return iterate(
next,
solution,
limit
)
}
return seed
}
var solution = 'hello world'
var candidate = iterate(getRandomString(solution.length), solution, 500)
console.log('candidate', candidate)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment