AdventOfCode/2020/15_haskell.ipynb

125 lines
2.8 KiB
Text

{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"puzzle <- readFile \"15.txt\"\n",
"plines = lines puzzle"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Day 15"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1618"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import qualified Data.Map as Map\n",
"import Data.List.Split\n",
"\n",
"nums = map read $ splitOn \",\" puzzle :: [Int]\n",
"\n",
"solve :: Int -> Int -> Map.Map Int Int -> Int\n",
"solve i n hist\n",
" | i == 2020 = n\n",
" | otherwise = solve (i+1) o $ Map.insert n (i-1) hist\n",
" where o = i - 1 - Map.findWithDefault (i-1) n hist\n",
"\n",
"initialize :: Int -> Map.Map Int Int -> Int\n",
"initialize i hist\n",
" | i == length nums - 1 = solve (i+1) (nums !! i) newMap\n",
" | otherwise = initialize (i+1) newMap\n",
" where newMap = Map.insert (nums !! i) i hist\n",
"\n",
"initialize 0 Map.empty"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Puzzle 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"548531"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import qualified Data.Map as Map\n",
"import Data.List.Split\n",
"\n",
"nums = map read $ splitOn \",\" puzzle :: [Int]\n",
"\n",
"next :: Int -> (Int, Map.Map Int Int) -> (Int, Map.Map Int Int)\n",
"next i (n, hist) = (o, Map.insert n (i-1) hist)\n",
" where o = i - 1 - Map.findWithDefault (i-1) n hist\n",
"\n",
"solve :: Int -> Int -> Map.Map Int Int -> Int\n",
"solve i n hist = fst $ foldl (flip next) (n, hist) [i..30000000-1]\n",
"\n",
"initialize :: Int -> Map.Map Int Int -> Int\n",
"initialize i hist\n",
" | i == length nums - 1 = solve (i+1) (nums !! i) newMap\n",
" | otherwise = initialize (i+1) newMap\n",
" where newMap = Map.insert (nums !! i) i hist\n",
"\n",
"initialize 0 Map.empty"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Haskell",
"language": "haskell",
"name": "haskell"
},
"language_info": {
"codemirror_mode": "Haskell",
"file_extension": ".hs",
"mimetype": "text/x-haskell",
"name": "haskell",
"pygments_lexer": "Haskell",
"version": "8.8.4"
}
},
"nbformat": 4,
"nbformat_minor": 4
}