Skip to content

Instantly share code, notes, and snippets.

@AndrasKovacs
Last active January 2, 2016 00:29
Show Gist options
  • Save AndrasKovacs/8223339 to your computer and use it in GitHub Desktop.
Save AndrasKovacs/8223339 to your computer and use it in GitHub Desktop.
The Boggle to end all Boggles has arrived! Runs in 60 usec on my machine. It uses a DAWG generated from the TWL06 Scrabble dictionary.
{-
Copyright (C) 2014 András Kovács
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-}
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import qualified Data.DAWG.Packed as DWG
import Data.Ix
import Data.Bits
import Data.List
import Data.Ord
import Criterion.Main
neighbours :: V.Vector [Int]
neighbours = 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))]
++ [[0..15]] -- i=16 is the starting position which has all positions as neighbours
findNode :: Char -> [DWG.Node] -> Maybe (DWG.Node)
findNode c (n:ns) = case compare c (DWG.char n) of
GT -> findNode c ns
EQ -> Just n
LT -> Nothing
findNode c [] = Nothing
finds :: DWG.Node -> UV.Vector Char -> [String]
finds node table = let
go node i visited = do
i' <- filter (not . testBit visited) $ V.unsafeIndex neighbours i
let chNodes = DWG.children node
currChar = UV.unsafeIndex table i'
case findNode currChar chNodes of
Just node' -> [[currChar] | DWG.endOfWord node'] ++
(map (currChar:) $ go node' i' (setBit visited i'))
_ -> []
in filter ((>2) . length) $ go node 16 (0 :: Int)
table = UV.fromList "ABCDEFGHIJKLMNOP"
main = do
dwg <- DWG.fromFile "words.dawg" -- pre-generated file
defaultMain [
bench "bench" $ nf (finds dwg) table]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment