-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattle.py
398 lines (331 loc) · 15 KB
/
battle.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
from __future__ import annotations
import argparse
import copy
import time
from dataclasses import dataclass
from typing import *
from enum import Enum
class Direction:
x: int
y: int
vertical: Optional[bool] = None
def __init__(self, x: int, y: int, vertical: Optional[bool] = None):
self.x = x
self.y = y
self.vertical = vertical
def __add__(self, other: Direction) -> Direction:
return Direction(self.x + other.x, self.y + other.y)
def __mul__(self, other: int) -> Direction:
return Direction(self.x * other, self.y * other)
@dataclass
class Ship:
size: int
first_piece: Direction
vertical: bool
def rectangle(self) -> Tuple[Direction, Direction]:
upper_left = self.first_piece + Direction(-1, -1)
if self.vertical:
bottom_right = self.first_piece + Direction(1, self.size)
else:
bottom_right = self.first_piece + Direction(self.size, 1)
return upper_left, bottom_right
def actual_box(self) -> Tuple[Direction, Direction]:
top = self.first_piece
if self.vertical:
bottom = self.first_piece + Direction(0, self.size - 1)
else:
bottom = self.first_piece + Direction(self.size - 1, 0)
return top, bottom
def find_rect_overlap(self, is_vertical: bool, size: int) -> Tuple[Direction, Direction]:
upper_left, bottom_right = self.rectangle()
if self.size == 0:
bottom_right = self.first_piece
size_adjustment = size - 1
if is_vertical:
upper_left = upper_left + Direction(0, -size_adjustment)
else:
upper_left = upper_left + Direction(-size_adjustment, 0)
return upper_left, bottom_right
class ShipException(Exception):
pass
class Domain:
domain_size: int
num_ships_remaining: int
ship_size: int
vertical_ships: List[List[bool]]
horizontal_ships: List[List[bool]]
board_size: int
def __init__(self, board_size: int, ship_size: int, num_ships: int):
self.ship_size = ship_size
self.vertical_ships = [[True for _ in range(board_size)] for _ in range(board_size)]
self.horizontal_ships = [[True for _ in range(board_size)] for _ in range(board_size)]
self.board_size = board_size
self.domain_size = board_size * board_size * 2
self.num_ships_remaining = num_ships
for x in range(board_size):
for y in range(board_size):
location = Direction(x, y)
vertical_ship = Ship(ship_size, location, True)
horizontal_ship = Ship(ship_size, location, False)
actual_box_top, actual_box_bottom = vertical_ship.actual_box()
if actual_box_bottom.x >= board_size or actual_box_bottom.y >= board_size:
direction = Direction(x, y, True)
self[direction] = False
actual_box_top, actual_box_bottom = horizontal_ship.actual_box()
if actual_box_bottom.x >= board_size or actual_box_bottom.y >= board_size:
direction = Direction(x, y, False)
self[direction] = False
def __getitem__(self, key: Direction):
if 0 <= key.x < self.board_size and 0 <= key.y < self.board_size:
if key.vertical:
return self.vertical_ships[key.y][key.x]
else:
return self.horizontal_ships[key.y][key.x]
def __setitem__(self, key: Direction, value):
if 0 <= key.x < self.board_size and 0 <= key.y < self.board_size:
if value == False and self[key]:
self.domain_size -= 1
if key.vertical:
self.vertical_ships[key.y][key.x] = False
else:
self.horizontal_ships[key.y][key.x] = False
def domain(self) -> Generator[Ship]:
for x in range(self.board_size):
for y in range(self.board_size):
if self.vertical_ships[y][x]:
yield Ship(self.ship_size, Direction(x, y, True), True)
if self.horizontal_ships[y][x]:
yield Ship(self.ship_size, Direction(x, y, False), False)
def set_ship(self, ship: Ship):
if self.num_ships_remaining == 0:
return
if ship.size == self.ship_size:
self.num_ships_remaining -= 1
upper_left, bottom_right = ship.find_rect_overlap(True, self.ship_size)
for x in range(upper_left.x, bottom_right.x + 1):
for y in range(upper_left.y, bottom_right.y + 1):
direction = Direction(x, y, True)
self[direction] = False
upper_left, bottom_right = ship.find_rect_overlap(False, self.ship_size)
for x in range(upper_left.x, bottom_right.x + 1):
for y in range(upper_left.y, bottom_right.y + 1):
direction = Direction(x, y, False)
self[direction] = False
if self.domain_size == 0 and self.num_ships_remaining > 0:
raise ShipException("No more possible ship locations")
elif self.domain_size < 0:
raise Exception("Domain size is negative")
def set_water(self, location: Direction):
for x in range(location.x - self.ship_size + 1, location.x + 1):
self[Direction(x, location.y, False)] = False
for y in range(location.y - self.ship_size + 1, location.y + 1):
self[Direction(location.x, y, True)] = False
if self.domain_size == 0 and self.num_ships_remaining > 0:
raise ShipException("No more possible ship locations")
elif self.domain_size < 0:
raise Exception("Domain size is negative")
def __repr__(self):
vertical_ships = [["V" if item else "." for item in row] for row in self.vertical_ships]
horizontal_ships = [["H" if item else "." for item in row] for row in self.horizontal_ships]
return "\n".join([" ".join(row) for row in vertical_ships]) + "\n\n" + "\n".join(
[" ".join(row) for row in horizontal_ships])
def remaining_ship_row(self, row: int, remaining_ship: int):
if remaining_ship == 0:
for x in range(self.board_size):
self.set_water(Direction(x, row, False))
elif remaining_ship < self.ship_size:
for x in range(self.board_size):
self[Direction(x, row, False)] = False
def remaining_ship_col(self, col: int, remaining_ship: int):
if remaining_ship == 0:
for y in range(self.board_size):
self.set_water(Direction(col, y, True))
elif remaining_ship < self.ship_size:
for y in range(self.board_size):
self[Direction(col, y, True)] = False
class Board:
ships: List[Ship]
size: int
submarine_domain: Domain
two_ship_domain: Domain
three_ship_domain: Domain
four_ship_domain: Domain
domains: List[Domain]
row_constraints: List[int]
col_constraints: List[int]
def board_repr(self) -> List[List[str]]:
board = [["." for _ in range(self.size)] for _ in range(self.size)]
for ship in self.ships:
if ship.vertical:
direction = Direction(0, 1)
else:
direction = Direction(1, 0)
if ship.size == 1:
board[ship.first_piece.y][ship.first_piece.x] = "S"
elif ship.vertical:
if ship.size == 2:
board[ship.first_piece.y][ship.first_piece.x] = "^"
board[ship.first_piece.y + 1][ship.first_piece.x] = "v"
elif ship.size == 3:
board[ship.first_piece.y][ship.first_piece.x] = "^"
board[ship.first_piece.y + 1][ship.first_piece.x] = "M"
board[ship.first_piece.y + 2][ship.first_piece.x] = "v"
elif ship.size == 4:
board[ship.first_piece.y][ship.first_piece.x] = "^"
board[ship.first_piece.y + 1][ship.first_piece.x] = "M"
board[ship.first_piece.y + 2][ship.first_piece.x] = "M"
board[ship.first_piece.y + 3][ship.first_piece.x] = "v"
else:
if ship.size == 2:
board[ship.first_piece.y][ship.first_piece.x] = "<"
board[ship.first_piece.y][ship.first_piece.x + 1] = ">"
elif ship.size == 3:
board[ship.first_piece.y][ship.first_piece.x] = "<"
board[ship.first_piece.y][ship.first_piece.x + 1] = "M"
board[ship.first_piece.y][ship.first_piece.x + 2] = ">"
elif ship.size == 4:
board[ship.first_piece.y][ship.first_piece.x] = "<"
board[ship.first_piece.y][ship.first_piece.x + 1] = "M"
board[ship.first_piece.y][ship.first_piece.x + 2] = "M"
board[ship.first_piece.y][ship.first_piece.x + 3] = ">"
return board
def __repr__(self):
return "\n".join(["".join(row) for row in self.board_repr()])
def __init__(self, size: int, ship_constraints: List[int] = None, row_constraints: List[int] = None,
col_constraints: List[int] = None):
self.size = size
if ship_constraints:
self.submarine_domain = Domain(size, 1, ship_constraints[0])
self.two_ship_domain = Domain(size, 2, ship_constraints[1])
self.three_ship_domain = Domain(size, 3, ship_constraints[2])
self.four_ship_domain = Domain(size, 4, ship_constraints[3])
self.domains = [self.submarine_domain, self.two_ship_domain, self.three_ship_domain, self.four_ship_domain]
self.row_constraints = row_constraints
self.col_constraints = col_constraints
self.ships = []
for row in range(size):
for domain in self.domains:
domain.remaining_ship_row(row, row_constraints[row])
for col in range(size):
for domain in self.domains:
domain.remaining_ship_col(col, col_constraints[col])
def set_ship(self, ship: Ship):
direction = ship.first_piece
vertical = ship.vertical
size = ship.size
self.ships.append(ship)
for domain in self.domains:
domain.set_ship(ship)
if vertical:
for y in range(direction.y, direction.y + size):
self.row_constraints[y] -= 1
if self.row_constraints[y] < 0:
raise ShipException("Ship does not fit in board")
self.col_constraints[direction.x] -= size
else:
self.row_constraints[direction.y] -= size
for x in range(direction.x, direction.x + size):
self.col_constraints[x] -= 1
if self.col_constraints[x] < 0:
raise ShipException("Ship does not fit in board")
if self.row_constraints[direction.y] < 0 or self.col_constraints[direction.x] < 0:
raise ShipException("Ship does not fit in board")
for domain in self.domains:
domain.remaining_ship_row(direction.y, self.row_constraints[direction.y])
domain.remaining_ship_col(direction.x, self.col_constraints[direction.x])
self.domains = [domain for domain in self.domains if domain.num_ships_remaining > 0]
def handle_simple_hints(self, board_str: List[List[str]]):
for row in range(self.size):
for col in range(self.size):
hint = board_str[row][col]
if hint == "S":
self.set_ship(Ship(1, Direction(col, row), False))
elif hint == ".":
for domain in self.domains:
domain.set_water(Direction(col, row, False))
def handle_complex_hints(self, board_str: List[List[str]]) -> List[Board]:
queue = [self]
for row in range(self.size):
for col in range(self.size):
hint = board_str[row][col]
if hint in ["^", "v", "<", ">", "M"]:
new_queue = []
for board in queue:
if board.validate_hint(Direction(col, row), hint):
new_queue.append(board)
else:
new_queue += board.find_hint(Direction(col, row), hint)
queue = new_queue
return queue
def find_hint(self, location: Direction, hint: str) -> List[Board]:
new_boards = []
for domain in self.domains:
for value in domain.domain():
new_board = copy.deepcopy(self)
try:
new_board.set_ship(value)
if new_board.board_repr()[location.y][location.x] == hint:
new_boards.append(new_board)
except:
pass
return new_boards
def validate_hint(self, location: Direction, hint: str) -> bool:
if self.board_repr()[location.y][location.x] == hint:
return True
def backtracking(self) -> Optional[Board]:
domains = sorted(self.domains, key=lambda x: x.domain_size)
if len(domains) == 0:
return self
domain = domains[0]
for move in domain.domain():
domain[move.first_piece] = False
new_board = copy.deepcopy(self)
try:
new_board.set_ship(move)
result = new_board.backtracking()
if result:
return result
except:
pass
def solve(self, board_str):
self.handle_simple_hints(board_str)
boards = self.handle_complex_hints(board_str)
for board in boards:
result = board.backtracking()
if result:
return result
if __name__ == "__main__":
# domain = Domain(10, 1, 1)
# ship = Ship(2, Direction(3, 3), True)
# domain.set_ship(ship)
# domain.set_water(Direction(3, 9, False))
# print(domain)
# print(domain.domain_size)
parser = argparse.ArgumentParser()
parser.add_argument(
"--inputfile",
type=str,
required=True,
help="The input file that contains the puzzles."
)
parser.add_argument(
"--outputfile",
type=str,
required=True,
help="The output file that contains the solution."
)
args = parser.parse_args()
file = open(args.inputfile, 'r')
board_str = file.read().splitlines()
board_str = [list(row) for row in board_str]
sizes = [int(x) for x in board_str[2]]
row_constraints = [int(x) for x in board_str[0]]
col_constraints = [int(x) for x in board_str[1]]
size = len(board_str[0])
board_str = board_str[3:]
board = Board(size, sizes, row_constraints, col_constraints)
final = board.solve(board_str)
write_file = open(args.outputfile, 'w')
write_file.write(final.__repr__())
print(final)
# print(board.four_ship_domain.num_ships_remaining)