Skip to content

Instantly share code, notes, and snippets.

@purarue
Last active July 21, 2020 00:58
Show Gist options
  • Save purarue/8b80c58ac92ad9fc1ada000753ad482c to your computer and use it in GitHub Desktop.
Save purarue/8b80c58ac92ad9fc1ada000753ad482c to your computer and use it in GitHub Desktop.
battleship score [interview question]
import pprint
import string
from typing import Tuple
def lookup_str_index(char: str):
return string.ascii_uppercase.index(char) + 1
def parse_coord(locstr: str) -> Tuple[int, int]:
return (int(locstr[0]), lookup_str_index(locstr[1]))
class Ship:
def __init__(self, locstr: str) -> 'Ship':
topleft, _, bottomright = locstr.partition(" ")
self.topleft = parse_coord(topleft)
self.bottomright = parse_coord(bottomright)
self.area = abs(self.bottomright[1] - self.topleft[1] + 1) \
* abs(self.bottomright[0] - self.topleft[0] + 1)
self.hitcounter = 0
def fire_at(self, coord: Tuple[int, int]) -> bool:
if self.topleft[0] <= coord[0] <= self.bottomright[0] and \
self.topleft[1] <= coord[1] <= self.bottomright[1]:
self.hitcounter += 1
return True
return False
def __str__(self) -> str:
return "({}, {}), area: {}, hits: {}".format(self.topleft, self.bottomright, self.area, self.hitcounter)
__repr__ = __str__
if __name__ == "__main__":
# return the number of ships that have been sunk, and the number of hits
# on non-sunken ships
gridSize = 4
ships = "1B 2C,2D 4D"
shipsHit = "2B 2D 3D 4D 4A"
# create ships
allShips = []
for ship in ships.split(","):
allShips.append(Ship(ship))
shots = []
# create artillery
for shot in shipsHit.split(" "):
shots.append(parse_coord(shot))
# fire each shot at every ship
for s in shots:
for sh in allShips:
sh.fire_at(s)
# calculate result
sunken_ships = 0
hits = 0
for s in allShips:
if s.area <= s.hitcounter:
sunken_ships += 1
else:
hits += s.hitcounter
# print result
print("{}, {}".format(sunken_ships, hits))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment