|
| 1 | +Everything reveals itself if we imagine a lookup table of "best path from A to |
| 2 | +B". For my own purposes I've made the functions parameterized by button pad, |
| 3 | +using `Maybe a`, where `Nothing` is the `A` key and `Just x` is the `x` key. |
| 4 | + |
| 5 | +```haskell |
| 6 | +type LookupTable a b = Map (Maybe a) (Map (Maybe a) [Maybe b]) |
| 7 | + |
| 8 | +type LookupTableLengths a = Map (Maybe a) (Map (Maybe a) Int) |
| 9 | + |
| 10 | +toLengths :: LookupTable a b -> LookupTableLengths a |
| 11 | +toLengths = fmap (fmap length) |
| 12 | +``` |
| 13 | + |
| 14 | +The key is that now these maps are composable: |
| 15 | + |
| 16 | +```haskell |
| 17 | +spellDirPathLengths :: Ord a => LookupTableLengths a -> [Maybe a] -> Int |
| 18 | +spellDirPathLengths mp xs = sum $ zipWith (\x y -> (mp M.! x) M.! y) xs (drop 1 xs) |
| 19 | + |
| 20 | +composeDirPathLengths :: Ord b => LookupTableLengths b -> LookupTable a b -> LookupTableLengths a |
| 21 | +composeDirPathLengths mp = (fmap . fmap) (spellDirPathLengths mp . (Nothing :)) |
| 22 | +``` |
| 23 | + |
| 24 | +That is, if you have the lookup table for two layers, you can compose them to |
| 25 | +create one big lookup table. |
| 26 | + |
| 27 | +```haskell |
| 28 | +data Dir = North | East | West | South |
| 29 | +data NumButton = Finite 10 |
| 30 | + |
| 31 | +dirPathChain :: [LookupTableLengths NumButton] |
| 32 | +dirPathChain = iterate (`composeDirPathLengths` dirPath @Dir) (dirPathCosts @Dir) |
| 33 | + |
| 34 | +solveCode :: Int -> [Maybe NumButton] -> Int |
| 35 | +solveCode n = spellDirPathLengths mp . (Nothing :) |
| 36 | + where |
| 37 | + lengthChain = dirPathChain !! (n - 1) |
| 38 | + mp = lengthChain `composeDirPathLengths` dirPath @NumButton |
| 39 | +```` |
| 40 | + |
| 41 | +The nice thing is that you only need to compute `dirPathChain` once, to get the |
| 42 | +final `LookupTableLengths` for a given `n`, and you can re-use it for |
| 43 | +everything. |
| 44 | + |
| 45 | +Generating the actual `LookupTable NumButton Dir` and `LookupTable Dir Dir` is |
| 46 | +the tricky part. For me I generated it based on the shortest path considering |
| 47 | +the third bot up the chain from the bottom: I used an *fgl* graph where the |
| 48 | +nodes were the state of three bots and the edges were the actions that the |
| 49 | +fourth "controller" would take, and computed the shortest path in terms of the |
| 50 | +fourth controller. This seems to be the magic number: anything higher and you |
| 51 | +get the same answer, anything lower and you get suboptimal final paths. |
0 commit comments