Last active
February 2, 2017 11:39
-
-
Save mykeels/ab835ca1a51a419a88f93b3527694b3f to your computer and use it in GitHub Desktop.
Hill-Climbing Algorithm implementation for the sphere function
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
//every metaheuristic needs -> | |
// - solution initialization function (must generate a random solution everytime) | |
// - fitness function | |
// - mutation function | |
// - clone function | |
function hillClimb() { | |
var sol1 = getRandomSolution(5); | |
var fit1 = getFitness(sol1); | |
for (var i = 1; i <= 1000; i++) { | |
var sol2 = mutate(sol1); | |
var fit2 = getFitness(sol2); | |
if (fit2 < fit1) { | |
sol1 = sol2; | |
fit1 = fit2; | |
} | |
console.log(fit1); | |
} | |
console.log(sol1); | |
return sol1; | |
} | |
// - solution initialization function | |
function getRandomSolution(width) { | |
var sol = []; | |
for (var i = 0; i < width; i++) { | |
sol.push((Math.random() * -10.24) + 5.12); | |
} | |
return sol; | |
} | |
// - fitness function | |
function getFitness(solution) { | |
var sum = 0; | |
for (var i = 0; i < solution.length; i++) { | |
sum += (solution[i] * solution[i]); | |
} | |
return sum; | |
} | |
// - mutation function | |
function mutate(solution) { | |
var newSol = clone(solution); | |
for (var i = 0; i < newSol.length; i++) { | |
var sol = newSol[i]; | |
if (Math.random() < 0.3) newSol[i] = sol + ((Math.random() * -2) + 1); | |
} | |
return newSol; | |
} | |
// - clone function | |
function clone(solution) { | |
return solution.slice(); | |
} | |
hillClimb(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment