Skip to content

Commit 3e01b28

Browse files
committed
adding HillCliming
1 parent 77ffb0e commit 3e01b28

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package aima.core.search.local
2+
3+
import aima.core.agent.Action
4+
import aima.core.search.{Problem, ProblemSearch, State, StateNode}
5+
6+
import scala.annotation.tailrec
7+
8+
/**
9+
*
10+
* <pre>
11+
* function HILL-CLIMBING(problem) returns a state that is a local maximum
12+
*
13+
* current &larr; MAKE-NODE(problem.INITIAL-STATE)
14+
* loop do
15+
* neighbor &larr; a highest-valued successor of current
16+
* if neighbor.VALUE &le; current.VALUE then return current.STATE
17+
* current &larr; neighbor
18+
* </pre>
19+
* <p>
20+
*
21+
* @author Shawn Garner
22+
*/
23+
object HillClimbing {
24+
25+
final case class StateValueNode(state: State, value: Double) extends State
26+
27+
def apply(stateToValue: State => Double)(problem: Problem): State = {
28+
29+
def makeNode(state: State) = StateValueNode(state, stateToValue(state))
30+
31+
def highestValuedSuccessor(current: StateValueNode): StateValueNode = {
32+
val successors = problem.actions(current).map(a => problem.result(current, a)).map(makeNode)
33+
34+
if (successors.isEmpty) {
35+
current
36+
} else {
37+
successors.maxBy(_.value)
38+
}
39+
40+
}
41+
42+
@tailrec def recurse(current: StateValueNode): State = {
43+
val neighbor = highestValuedSuccessor(current)
44+
if (neighbor.value <= current.value) {
45+
current.state
46+
} else {
47+
recurse(neighbor)
48+
}
49+
}
50+
51+
recurse(makeNode(problem.initialState))
52+
}
53+
54+
}

0 commit comments

Comments
 (0)