Created
March 7, 2024 20:54
-
-
Save mlivingston40/39772d703ee261461d6875899efd1ab6 to your computer and use it in GitHub Desktop.
For the game battleship, count the unique ships on the board for a dynamically sized board
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
`X` means part of a ship is here | |
`.` means it is an empty spot | |
""" | |
board = [ | |
["X", ".", "X", ".", "X", "X"], | |
["X", ".", ".", ".", ".", "."], | |
["X", ".", "X", ".", "X", "."] | |
] | |
# the final count we want to return | |
unique_ships = 0 | |
# tracking if there is an X in the vertical row above the current row | |
ship_index_tracker = {} | |
for r in board: | |
# for row aka r in board | |
# the index of the current column of the row | |
i = 0 | |
# evaluate each element of the row `r` | |
while len(r) > 0: | |
if not ship_index_tracker.get(i) and r[0] == 'X': | |
# if this is the last column of the row | |
if len(r) == 1: | |
unique_ships += 1 | |
else: | |
# if there is a space next to it then this means end of ship | |
if r[1] == '.': | |
unique_ships += 1 | |
# update the tracker to inform the next row aka r+1 if there's a ship part above it | |
if r[0] == 'X': | |
ship_index_tracker[i] = True | |
else: | |
ship_index_tracker[i] = False | |
# remove the current element of the row being evaluated | |
r.pop(0) | |
# move the index of the row | |
i += 1 | |
print(f'The number of unique_ships on the board: {unique_ships}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment