-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhill.py
52 lines (39 loc) · 1.48 KB
/
hill.py
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Thomas Fiorilla, fork of Anthony Tiongson
# Fork of Anthony's code so that the hill-climbing is its own module and class; 95% of code is Anthony's, remaining 5% is adapting code to be a class
import copy
import bfirst
import evaluate
import random
import board
import time
class Hill:
def __init__(self, board):
self.puzzle = copy.deepcopy(board)
self.averageScore = []
def climb(self, iterations):
start = time.time()
n_max = self.puzzle.boardSize - 1
newPuzzle = copy.deepcopy(self.puzzle)
count = 1
while iterations > 0:
# print('Iteration: ' + str(count))
eval1 = evaluate.evaluate(self.puzzle.boardBuilt, self.puzzle.boardSize).value
i_r = random.randint(0, n_max)
if i_r == n_max:
j_r = random.randint(0, (n_max - 1))
else:
j_r = random.randint(0, n_max)
newPuzzle.boardBuilt[i_r][j_r] = board.valid(i_r, j_r, self.puzzle.boardSize)
eval2 = evaluate.evaluate(newPuzzle.boardBuilt, self.puzzle.boardSize).value
if eval2 >= eval1:
# print('Hill Climbing mutation better')
self.puzzle = copy.deepcopy(newPuzzle)
eval = evaluate.evaluate(self.puzzle.boardBuilt, self.puzzle.boardSize).value
else:
# print('Original puzzle better or as good')
eval = evaluate.evaluate(self.puzzle.boardBuilt, self.puzzle.boardSize).value
count += 1
iterations -= 1
self.score = evaluate.evaluate(self.puzzle.boardBuilt, self.puzzle.boardSize).value
end = time.time()
self.evalTime = (end - start) * 1000