Simulated Annealing
javascript
Solution
Doing a quick search on GitHub found https://github.com/ebobby/Jsqueens which uses simulated annealing to solve the 9 queens problem. Here's the relevant code:
/**
* @author Francisco Soto <ebobby@gmail.com>
*/
var SimulatedAnnealing = (function () {
var coolingFactor = 0.0,
stabilizingFactor = 0.0,
freezingTemperature = 0.0,
currentSystemEnergy = 0.0,
currentSystemTemperature = 0.0,
currentStabilizer = 0.0,
generateNewSolution = null,
generateNeighbor = null,
acceptNeighbor = null;
function _init (options) {
coolingFactor = options.coolingFactor;
stabilizingFactor = options.stabilizingFactor;
freezingTemperature = options.freezingTemperature;
generateNewSolution = options.generateNewSolution;
generateNeighbor = options.generateNeighbor;
acceptNeighbor = options.acceptNeighbor;
currentSystemEnergy = generateNewSolution();
currentSystemTemperature = options.initialTemperature;
currentStabilizer = options.initialStabilizer;
}
function _probabilityFunction (temperature, delta) {
if (delta < 0) {
return true;
}
var C = Math.exp(-delta / temperature);
var R = Math.random();
if (R < C) {
return true;
}
return false;
}
function _doSimulationStep () {
if (currentSystemTemperature > freezingTemperature) {
for (var i = 0; i < currentStabilizer; i++) {
var newEnergy = generateNeighbor(),
energyDelta = newEnergy - currentSystemEnergy;
if (_probabilityFunction(currentSystemTemperature, energyDelta)) {
acceptNeighbor();
currentSystemEnergy = newEnergy;
}
}
currentSystemTemperature = currentSystemTemperature - coolingFactor;
currentStabilizer = currentStabilizer * stabilizingFactor;
return false;
}
currentSystemTemperature = freezingTemperature;
return true;
}
return {
Initialize: function (options) {
_init(options);
},
Step: function () {
return _doSimulationStep();
},
GetCurrentEnergy: function () {
return currentSystemEnergy;
},
GetCurrentTemperature: function () {
return currentSystemTemperature;
}
};
})();
Problem
I want to code simulated annealing in HTML and JavaScript. I want to code it for placement, but for simplicity I am assuming that all the cells are in one row. I have around 30 cells. I looked for some material online but I couldn't find code to start with. My pseudocode is as follows: ``` Simulated_Annealing{ S = initial solution T = initial temperature (>0) while( T > 0 ) { S’ = pick a random neighbor to S C = cost of S – cost of S’ if( C > 0 ){ S = S’ } else { r = random number in range [0…1] m = 1/e| C/T | if( r < m ) { S = S’ } } T = reduced T; } } ``` Any help is appreciated. Thanks.