109 lines
2.2 KiB
Text
109 lines
2.2 KiB
Text
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"puzzle <- readFile \"09.txt\"\n",
|
|
"plines = lines puzzle"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Day 09"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Puzzle 1"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"31161678"
|
|
]
|
|
},
|
|
"metadata": {},
|
|
"output_type": "display_data"
|
|
}
|
|
],
|
|
"source": [
|
|
"num :: Int -> Int\n",
|
|
"num idx = read $ plines !! idx\n",
|
|
"\n",
|
|
"test :: Int -> Int -> Bool\n",
|
|
"test idx target = or [a + b == target | i <- [idx..idx+24], j <- [i+1..idx+24], let [a,b] = map num [i,j], a/=b]\n",
|
|
"\n",
|
|
"head [num i | i <- [25..length plines-1], not $ test (i-25) $ num i]"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Puzzle 2"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"5453868"
|
|
]
|
|
},
|
|
"metadata": {},
|
|
"output_type": "display_data"
|
|
}
|
|
],
|
|
"source": [
|
|
"sumRange :: Int -> Int -> Int\n",
|
|
"sumRange start end = sum $ map num [start..end]\n",
|
|
"\n",
|
|
"findRange :: Int -> Int -> Maybe Int\n",
|
|
"findRange idx target\n",
|
|
" | target == 0 = Just $ idx - 1\n",
|
|
" | target < 0 = Nothing\n",
|
|
" | otherwise = findRange (idx+1) $ target - num idx\n",
|
|
"\n",
|
|
"minmax :: Int -> Maybe Int -> Int\n",
|
|
"minmax a (Just b) = minimum x + maximum x\n",
|
|
" where x = map num [a..b]\n",
|
|
"\n",
|
|
"head [minmax i j | i <- [0..length plines-1], let j = findRange (i+1) $ 31161678 - num i, case j of Just _ -> True; _ -> False]"
|
|
]
|
|
}
|
|
],
|
|
"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
|
|
}
|