-
Notifications
You must be signed in to change notification settings - Fork 225
Expand file tree
/
Copy pathsimulatedAnnealing.js
More file actions
34 lines (33 loc) · 918 Bytes
/
simulatedAnnealing.js
File metadata and controls
34 lines (33 loc) · 918 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class SimulatedAnnealing {
constructor(hill, initial, k) {
this.states = hill.getStates();
this.initial = initial;
this.current = this.initial;
this.k = k;
}
anneal(temperature) {
let nextState = this.getRandomState();
let diff = this.states[nextState] - this.states[this.current];
if (diff > 0) {
this.current = nextState;
} else {
let p = Math.exp((diff) / parseInt(this.k * temperature));
if (Math.random() < p) {
this.current = nextState;
}
}
return {
state: this.current,
temp: temperature
};
}
/**
* @see https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values
* @returns {Number}
*/
getRandomState() {
let mini = 0;
let maxi = this.states.length;
return Math.floor(Math.random() * (maxi - mini)) + mini;
}
}