Skip to content

Instantly share code, notes, and snippets.

@Ch4s3
Created May 15, 2019 20:22
Show Gist options
  • Save Ch4s3/fd5aefb693f7ea6330ec72a6b8587f38 to your computer and use it in GitHub Desktop.
Save Ch4s3/fd5aefb693f7ea6330ec72a6b8587f38 to your computer and use it in GitHub Desktop.
defmodule Boggle do
def full_match(dictionary, word) do
case Enum.member?(dictionary, word) do
true -> word
false -> nil
end
end
def solve_location(dictionary, board, location, word) do
# concat the word and the next letter to be tried
new_word = word <> Map.get(board, location)
# remove the letter from the board
board = Map.delete(board, location)
# is this a whole word
full_match = full_match(dictionary, new_word)
case full_match do
nil ->
# if not recursively build up words
get_neighbors(board, location)
|> Enum.reduce([new_word], fn(neighbor, acc) ->
[acc | solve_location(dictionary, board, neighbor, new_word)]
end)
_ ->
[new_word]
end
|> List.flatten()
end
def get_neighbors(board, {x,y}) do
# possible neighbor locations
[
{x + 1, y},
{x - 1, y},
{x, y + 1},
{x, y - 1},
{x - 1, y - 1},
{x + 1, y + 1},
{x + 1, y - 1},
{x - 1, y + 1}
]
|> Enum.filter(&Map.has_key?(board, &1))
end
def key_board(_board, map, 0, _), do: map
def key_board(board, map, board_dimensions, column) do
# grab the first row
[row1 | rest] = board
# nap over the row with indexes and reduce the indexes/current column
# into a map as the key with the letter as the value
new_map =
Enum.with_index(row1)
|> Enum.reduce(map, fn({letter, row_index}, map) -> Map.put(map, {column, row_index}, letter) end)
key_board(rest, new_map, board_dimensions - 1, column + 1)
end
def solve(dictionary, board, board_dimensions) do
keyed_board = key_board(board, %{}, board_dimensions, 0)
for x <- 0..(board_dimensions - 1), y <- 0..(board_dimensions - 1) do
solve_location(dictionary, keyed_board, {x, y}, "")
end
|> List.flatten()
|> Enum.filter(fn word -> Enum.member?(dictionary, word) end)
|> IO.inspect
end
end
board = [
["c","a","t"],
["a", "r", "o"],
["n", "a", "m"]
]
dictionary = ["cat", "toam", "arm", "art", "cram", "rot", "wall", "mart"]
Boggle.solve(dictionary, board, 3)
@Ch4s3
Copy link
Author

Ch4s3 commented May 15, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment