-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathmisscannibals.py
85 lines (56 loc) · 2.04 KB
/
misscannibals.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
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
82
83
84
85
from search import *
class MissCannibals(Problem):
def __init__(self, M=3, C=3, goal=(0, 0, False)):
initial = (M, C, True)
self.M = M
self.C = C
super().__init__(initial, goal)
# YOUR CODE GOES HERE
def goal_test(self, state):
return state == self.goal
def is_valid(self, state):
# checks that M and R are within range 0-initial
if state[0] < 0 or state[0] > self.initial[0]:
return False
if state[1] < 0 or state[1] > self.initial[1]:
return False
if state[0] < state[1] and state[0] != 0:
return False
mr = self.initial[0] - state[0]
cr = self.initial[1] - state[1]
if mr < cr and mr != 0:
return False
return True
def result(self, state, action):
temp = list(state)
# boat on left
if temp[2]:
temp[0] -= action.count('M')
temp[1] -= action.count('C')
# boat on right
else:
temp[0] += action.count('M')
temp[1] += action.count('C')
temp[2] = not temp[2]
return tuple(temp)
def actions(self, state):
actions = []
if self.is_valid(self.result(state, 'M')):
actions.append('M')
if self.is_valid(self.result(state, 'MM')):
actions.append('MM')
if self.is_valid(self.result(state, 'MC')):
actions.append('MC')
if self.is_valid(self.result(state, 'CC')):
actions.append('CC')
if self.is_valid(self.result(state, 'C')):
actions.append('C')
return actions
if __name__ == '__main__':
mc = MissCannibals(3, 3)
#print(mc.initial)
# print(mc.actions((3, 2, True))) # Test your code as you develop! This should return ['CC', 'C', 'M']
path = depth_first_graph_search(mc).solution()
print(path)
path = breadth_first_graph_search(mc).solution()
print(path)