-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhill_climbing.py
More file actions
81 lines (59 loc) · 2.1 KB
/
hill_climbing.py
File metadata and controls
81 lines (59 loc) · 2.1 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/bin/env python3
import random
# (valor, tamanho)
TIPOS = [ (1,3), (4,6), (5,7) ]
def stateValue(state, types):
return sum((e * tp[0]) for (e, tp) in zip(state, types))
def stateSize(state, types):
return sum((e * tp[1]) for (e, tp) in zip(state, types))
def stateIsValid(state, types, max_size):
return stateSize(state, types) <= max_size
def newListWithValueAt(lst, pos, value):
newList = lst.copy()
newList[pos] = value
return newList
def expandState(state):
return [ newListWithValueAt(state, i, state[i]+1) for i in range(len(state)) ]
def isPositiveState(state):
for i in range(len(state)):
if state[i] < 0:
return False
return True
def regressState(state):
indices = []
regression = [ newListWithValueAt(state, i, state[i]-1) for i in range(len(state)) ]
regression = list(filter(isPositiveState, regression))
return regression
def neighborhood(state):
expandedStates = expandState(state)
regressionStates = regressState(state)
newStates = expandedStates + regressionStates
return newStates
def getNeighbor(state, types, maxsize):
newStates = neighborhood(state)
newStates = list(filter(lambda x: stateIsValid(x, types, maxsize), newStates))
aux = random.randint(0,len(newStates)-1)
neighbor = newStates[aux]
return neighbor
def hillClimb(types, max_size):
state = [0 for i in types]
while True:
newStates = expandState(state)
validStates = list(
filter(
lambda state: stateIsValid(state, types, max_size),
newStates,
)
)
if not validStates:
return state
statesWithValues = []
for st in validStates:
statesWithValues.append( (st, stateValue(st, types)) )
(bestState, value) = max( statesWithValues, key=lambda st: st[1] )
#print(bestState)
state = bestState
if __name__ == "__main__":
result = hillClimb(TIPOS, 19)
print(result)
print("Custo da solução: "+str(stateSize(result, TIPOS))+", Valor da solução: "+str(stateValue(result, TIPOS)))