1 module Main(main) where
3 import Data.List ((\\), nub, sortOn)
4 import Data.Bits (popCount)
5 import Data.Maybe (fromMaybe)
20 part1 = print $ length $ tail $ fromMaybe [] $ aStar [[(1, 1)]] []
23 part2 = do print $ length $ tail $ edl 50 [[(1, 1)]] []
24 putStrLn $ showRoomR 30 25 $ edl 50 [[(1, 1)]] []
27 -- extractJust :: Maybe [a] -> [a]
28 -- extractJust Nothing = []
29 -- extractJust (Just x) = x
31 isWall :: Int -> Int -> Bool
32 isWall x y = odd $ popCount n
34 n = x*x + 3*x + 2*x*y + y + y*y + seed
37 showRoom w h = showRoomR w h []
39 showRoomR w h reached = unlines rows
41 rows = [row x | x <- [0..h]]
42 row x = [showCell x y | y <- [0..w]]
43 showCell x y = if (isWall x y)
45 else if (x, y) `elem` reached
50 aStar :: [[Pos]] -> [Pos] -> Maybe [Pos]
52 aStar (currentTrail:trails) closed =
53 if isGoal (head currentTrail) then Just currentTrail
54 else if (head currentTrail) `elem` closed then aStar trails closed
55 else aStar newAgenda ((head currentTrail): closed)
57 sortOn (\a -> trailCost a) $
58 trails ++ (candidates currentTrail closed)
59 trailCost t = estimateCost (head t) + length t - 1
62 -- exhaustive depth-limited
63 edl :: Int -> [[Pos]] -> [Pos] -> [Pos]
64 edl _ [] closed = nub closed
65 edl limit (currentTrail:trails) closed =
66 if (length currentTrail) > (limit+1) then edl limit trails ((head currentTrail):closed)
67 else if (head currentTrail) `elem` closed then edl limit trails closed
68 else edl limit newAgenda ((head currentTrail):closed)
69 where newAgenda = trails ++ (candidates currentTrail closed)
71 candidates :: [Pos] -> [Pos] -> [[Pos]]
72 candidates currentTrail closed = newCandidates
74 (candidate:trail) = currentTrail
75 succs = legalSuccessors $ successors candidate
76 nonloops = (succs \\ trail) \\ closed
77 newCandidates = map (\n -> n:candidate:trail) nonloops
82 isLegal :: Pos -> Bool
84 x >= 0 && y >= 0 && (not $ isWall x y)
86 successors :: Pos -> [Pos]
87 successors (x, y) = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]
89 legalSuccessors :: [Pos] -> [Pos]
90 legalSuccessors = filter (isLegal)
92 estimateCost :: Pos -> Int
93 estimateCost (x, y) = abs (x - gx) + abs (y - gy)
94 where (gx, gy) = goal1