Last active
April 23, 2021 16:54
-
-
Save jcalcutt/8e592d071f71eb80ead0ac546342bab3 to your computer and use it in GitHub Desktop.
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
from typing import List | |
def word_count(board: List[List[str]], word: str) -> int: | |
"""For a given 2-dimensional 'board' of characters, represented by a list of lists, calculate | |
the number of times a given word appears in the board, either horizontally, vertically, or diagonally | |
(left-to-right) | |
Parameters | |
---------- | |
board : List[List[str]] | |
A 2-D 'board' of letters, represented by a list of (string) lists, e.g. | |
[["A", "B" "C"], | |
["B", "B", "C"], | |
["C", "B", "C"]] | |
word : str | |
word to 'search' for in board, e.g. "ABC" | |
Returns | |
------- | |
int | |
Count of times word appears in board, e.g. 3 | |
""" | |
board_length = len(board[0]) | |
board_height = len(board) | |
total_count = 0 | |
# loop through horizontal arrays | |
if len(word) <= board_length: | |
for arr in board: | |
total_count += count_str_in_arr(arr, word) | |
# loop through vertical | |
if board_height >= len(word): | |
for i in range(board_length): | |
vert_arr = [] | |
for arr in board: | |
vert_arr.append(arr[i]) | |
total_count += count_str_in_arr(vert_arr, word) | |
# logic to create diagonal arrays - iterate over all top rows and columns on left of board | |
# loop through number of rows in board | |
for l in range(board_length): | |
# loop positions in row | |
for h in range(board_height): | |
# don't want to repeat elements | |
if l >= 1 and h > 0: | |
continue | |
diag_arr = [] | |
# logic to create diagonal array given a starting point | |
for j, arr in zip(range(board_length), board[l:]): | |
if j+h <= board_length - 1: | |
diag_arr.append(arr[j+h]) | |
# save some time ...no point checking if word not long enough | |
if len(diag_arr) >= len(word): | |
total_count += count_str_in_arr(diag_arr, word) | |
return total_count | |
def count_str_in_arr(arr: List[str], word: str) -> int: | |
"""Count the number of occurences of a word in a list of letters. Word occurences can be overlapping | |
Parameters | |
---------- | |
arr : List[str] | |
An array of individual letters, e.g. ["A", "B", "C", "A", "B", "C"] | |
word : str | |
word to 'search' for in board, e.g. "ABC" | |
Returns | |
------- | |
int | |
Count of times word appears in array, e.g. 2 | |
""" | |
arr_str = ''.join(arr) | |
occurences = 0 | |
for i in range(len(arr_str)): | |
if arr_str[i:i+(len(word))] == word: | |
occurences +=1 | |
return occurences |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment