-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
87 lines (66 loc) · 2.62 KB
/
utils.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
dough_length = 500
biscuits = {
0: {"length": 4, "value": 6, "defects": {"a": 4, "b": 2, "c": 3}, "id": 0},
1: {"length": 8, "value": 12, "defects": {"a": 5, "b": 4, "c": 4}, "id": 1},
2: {"length": 2, "value": 1, "defects": {"a": 1, "b": 2, "c": 1}, "id": 2},
3: {"length": 5, "value": 8, "defects": {"a": 2, "b": 3, "c": 2}, "id": 3},
}
MAX_BISCUIT_LENGTH = max(b["length"] for b in biscuits.values())
with open("defects.csv") as f:
lines = f.readlines()
defects = [line.strip().split(",") for line in lines[1:]]
# Defects never occur at precise integer coordinates, so a defect will never be shared by two tiles.
defect_counts = {}
for x, y in defects:
x = int(float(x))
if x not in defect_counts:
defect_counts[x] = {"a": 0, "b": 0, "c": 0}
defect_counts[x][y] += 1
for x in range(dough_length):
if x not in defect_counts:
defect_counts[x] = {"a": 0, "b": 0, "c": 0}
def check_solution(sol, debug=False):
last_position_with_biscuit = -1
sol = sorted(sol, key=lambda x: x[0])
value = 0
valid_sol = []
is_valid = True
for i, (x, y) in enumerate(sol):
if x < 0:
if debug:
print("Negative x", x, y)
is_valid = False
continue
if x + biscuits[y]["length"] > dough_length:
if debug:
print("Biscuit too long", x, y)
is_valid = False
continue
defect_counts_for_biscuit = {"a": 0, "b": 0, "c": 0}
for j in range(x, x + biscuits[y]["length"]):
if j in defect_counts:
for k in defect_counts[j]:
defect_counts_for_biscuit[k] += defect_counts[j][k]
if x <= last_position_with_biscuit:
if debug:
print("Biscuits overlap", x, y)
is_valid = False
continue
defects_match = True
for k in defect_counts_for_biscuit:
if defect_counts_for_biscuit[k] > biscuits[y]["defects"][k]:
if debug:
print("Defects don't match", x, y, k, defect_counts_for_biscuit, biscuits[y]["defects"])
defects_match = False
break
if not defects_match:
is_valid = False
continue
last_position_with_biscuit = x + biscuits[y]["length"] - 1
value += biscuits[y]["value"]
valid_sol.append((x, y))
return value, valid_sol, is_valid
def save_solution(sol, filename):
with open(filename, "w") as f:
for x, y in sol:
f.write("{},{}\n".format(x, y))