Skip to content

Instantly share code, notes, and snippets.

@AndrasKovacs
Last active December 18, 2015 17:49
Show Gist options
  • Save AndrasKovacs/5821189 to your computer and use it in GitHub Desktop.
Save AndrasKovacs/5821189 to your computer and use it in GitHub Desktop.
Getting all words out of Boggle tables.
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import qualified Data.ByteString.Char8 as B
import Data.Ix
import Text.Printf
import Data.List
import Data.Ord
import System.Environment
neighbors :: V.Vector [Int]
neighbors = V.fromList [[4*i + j |
(i,j) <- range ((x-1, y-1), (x+1, y+1)),
inRange ((0, 0), (3, 3)) (i,j),
(i,j) /= (x, y)] |
(x, y) <- range ((0, 0), (3, 3))]
finds :: UV.Vector Char -> [B.ByteString] -> [B.ByteString]
finds table = let
step x paths = [n:p:ps | p:ps <- paths,
x == table `UV.unsafeIndex` p,
n <- neighbors `V.unsafeIndex` p,
notElem n ps]
start = map (:[]) [0..15]
in filter (not . null . B.foldr step start)
main :: IO ()
main = do
args <- getArgs
case args of
[dictFile, tableSpec] -> do
dict <- fmap (filter ((>2) . B.length) . B.lines) $ B.readFile dictFile
let table = UV.fromList tableSpec
found = sortBy (flip $ comparing B.length) (finds table dict)
printf "\n%d finds:\n%s" (length found) (show found)
_ -> putStrLn "usage: Boggle [dictFile] [table]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment