-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver2.py
112 lines (96 loc) · 2.73 KB
/
solver2.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import copy
b = [2,2] # input bound
n = 5 # number of states
def cal_size(x):
s = 1
for i in x:
s = s * (i + 1)
return s
nb = cal_size(b)
X = []
Y = []
for i in range(nb):
X += [[0.0] * n]
Y += [[0.0] * n]
def copyXY():
for i in range(nb):
for j in range(n):
Y[i][j] = X[i][j]
def oneStep():
copyXY();
delta = -1
for i in range(nb):
for j in range(n):
assignXY(i, j)
delta = max(abs(X[i][j] - Y[i][j]),delta)
return delta
def assignXY(i,j):
ax = single_to_multi(i)
# state 0
if j == 0:
if ax[0]>=2:
X[i][j] = max([X[m2s(ax)][4],X[m2s([ax[0]-1,ax[1]])][1],X[m2s([ax[0]-2,ax[1]])][2]])
elif ax[0]>=1:
X[i][j] = max([X[m2s(ax)][4], X[m2s([ax[0] - 1, ax[1]])][1]])
else:
X[i][j] = X[m2s(ax)][4]
# state 1
elif j == 1:
if ax[0]>=2 and ax[1]>=2:
X[i][j] = max(
[X[m2s(ax)][4], 0.2 * X[m2s([ax[0] - 1, ax[1] - 1])][4] + 0.8 * X[m2s([ax[0] - 1, ax[1] - 1])][3],
0.1 * X[m2s([ax[0] - 2, ax[1] - 2])][4] + 0.9 * X[m2s([ax[0] - 2, ax[1] - 2])][3]])
elif ax[0]>=1 and ax[1]>=1:
X[i][j] = max(
[X[m2s(ax)][4], 0.2 * X[m2s([ax[0] - 1, ax[1] - 1])][4] + 0.8 * X[m2s([ax[0] - 1, ax[1] - 1])][3]])
else:
X[i][j] = X[m2s(ax)][4]
# state 2
elif j == 2:
if ax[0]>=2 and ax[1]>=2:
X[i][j] = max(
[X[m2s(ax)][4], 0.1 * X[m2s([ax[0] - 1, ax[1] - 1])][4] + 0.9 * X[m2s([ax[0] - 1, ax[1] - 1])][3],
0.01 * X[m2s([ax[0] - 2, ax[1] - 2])][4] + 0.99 * X[m2s([ax[0] - 2, ax[1] - 2])][3]])
elif ax[0]>=1 and ax[1]>=1:
X[i][j] = max(
[X[m2s(ax)][4], 0.1 * X[m2s([ax[0] - 1, ax[1] - 1])][4] + 0.9 * X[m2s([ax[0] - 1, ax[1] - 1])][3]])
else:
X[i][j] = X[m2s(ax)][4]
# state 3
elif j == 3:
X[i][j] = 1
# state 4
else:
X[i][j] = X[i][j]
def single_to_multi(i):
ax = copy.copy(b)
ti = i
for k in range(len(b)-1, -1, -1):
ax[k] = ti // cal_size(b[:k])
ti -= ax[k] * cal_size(b[:k])
return ax
def m2s(x):
return multi_to_single(x)
def multi_to_single(x):
i = 0
for k in range(len(b)-1, -1, -1):
i += x[k] * cal_size(b[:k])
return i
def next_bound(x):
for i in range(len(x)):
if x[i]>0:
x[i] -= 1
return x
if x[i]==0:
x[i] = b[i]
return None
def iterate(epsilon):
i = 0
while True:
delta = oneStep()
i += 1
print(i)
if delta <= epsilon:
break
return X[nb-1][0]
print(iterate(0.00000000000000001))