Skip to content

Commit

Permalink
day17
Browse files Browse the repository at this point in the history
  • Loading branch information
ilya-bobyr committed Dec 19, 2019
1 parent e208e56 commit 1888245
Show file tree
Hide file tree
Showing 7 changed files with 2,096 additions and 0 deletions.
30 changes: 30 additions & 0 deletions day17/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Copyright Ilya Bobyr (c) 2019

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

* Neither the name of Ilya Bobyr nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1 change: 1 addition & 0 deletions day17/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# day17
2 changes: 2 additions & 0 deletions day17/Setup.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import Distribution.Simple
main = defaultMain
24 changes: 24 additions & 0 deletions day17/day17.cabal
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: day17
version: 0.1.0.0
-- synopsis:
-- description:
homepage: https://github.com/ilya-bobyr/advent-of-code-2018/day17#readme
license: BSD3
license-file: LICENSE
author: Ilya Bobyr
maintainer: [email protected]
copyright: (c) 2018 Ilya Bobyr
category: Web
build-type: Simple
cabal-version: >=1.10
extra-source-files: README.md

executable day17
hs-source-dirs: src
main-is: Main.hs
default-language: Haskell2010
ghc-options: -O2 -fdiagnostics-color=always
build-depends: base >= 4.7 && < 5
, array
, control-bool
, parsec
1,728 changes: 1,728 additions & 0 deletions day17/output1

Large diffs are not rendered by default.

247 changes: 247 additions & 0 deletions day17/src/Main.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import Control.Bool ((<&&>))
import Control.Monad (foldM, sequence)
import Control.Monad.ST (ST, runST)
import Data.Array.MArray (readArray, writeArray)
import qualified Data.Array.MArray as MA
import Data.Array (Array)
import Data.Array.ST (STArray)
import Data.List (foldl', intercalate)
import Data.Maybe (catMaybes)
import System.Environment (getArgs)
import System.IO (Handle, hGetContents, IOMode(ReadMode), stdin, withFile)
import Text.Parsec (parse)
import Text.Parsec.Char (digit, string, newline)
import Text.Parsec.Combinator (eof, many1, sepEndBy)
import Text.Parsec.Prim (try, (<|>))
import Text.Parsec.String (Parser)

-- import Debug.Trace (traceM)

data BoardCell = Sand
| Clay
| MovingWater
| StillWater
deriving (Eq)

instance Show BoardCell where
show Sand = "."
show Clay = "#"
show MovingWater = "|"
show StillWater = "~"

flowAbove :: BoardCell -> Bool
flowAbove = \case Clay -> True
StillWater -> True
_ -> False

type Board s = STArray s (Int, Int) BoardCell
type IBoard = Array (Int, Int) BoardCell

showBoard :: Board s -> ST s String
showBoard board = do
((minY, minX), (maxY, maxX)) <- MA.getBounds board
let asChar = \case Sand -> '.'
Clay -> '#'
MovingWater -> '|'
StillWater -> '~'

intercalate "\n" <$>
sequence [
sequence [
asChar <$> readArray board (y, x) | x <- [minX..maxX]]
| y <- [minY..maxY]]

data InputCommand = Horizontal Int (Int, Int)
| Vertical (Int, Int) Int
deriving (Eq, Show)

horizontalCommandParser :: Parser InputCommand
horizontalCommandParser = do
_ <- string "y="
y <- read <$> many1 digit
_ <- string ", x="
minX <- read <$> many1 digit
_ <- string ".."
maxX <- read <$> many1 digit
return $ Horizontal y (minX, maxX)

verticalCommandParser :: Parser InputCommand
verticalCommandParser = do
_ <- string "x="
x <- read <$> many1 digit
_ <- string ", y="
minY <- read <$> many1 digit
_ <- string ".."
maxY <- read <$> many1 digit
return $ Vertical (minY, maxY) x

commandParser :: Parser InputCommand
commandParser =
try horizontalCommandParser
<|> verticalCommandParser

inputParser :: Parser [InputCommand]
inputParser = do
commands <- commandParser `sepEndBy` newline
eof
return commands

commandBounds :: InputCommand -> ((Int, Int), (Int, Int))
commandBounds (Horizontal y (minX, maxX)) = ((y, minX), (y, maxX))
commandBounds (Vertical (minY, maxY) x) = ((minY, x), (maxY, x))

buildBoard :: [InputCommand] -> ST s (Board s)
buildBoard commands =
let buildBounds ((!minY, !minX), (!maxY, !maxX))
((cMinY, cMinX), (cMaxY, cMaxX)) =
let minX' = if cMinX < minX then cMinX else minX
maxX' = if cMaxX > maxX then cMaxX else maxX
minY' = if cMinY < minY then cMinY else minY
maxY' = if cMaxY > maxY then cMaxY else maxY
in ((minY', minX'), (maxY', maxX'))

bounds =
foldl' buildBounds ((0, 500), (0, 500))
$ map commandBounds commands

extendXBy dx ((!minY, !minX), (!maxY, !maxX)) =
((minY, minX - dx), (maxY, maxX + dx))

applyCommand :: Board s -> InputCommand -> ST s (Board s)
applyCommand board (Horizontal y (minX, maxX)) = do
mapM_ (\x -> writeArray board (y, x) Clay) [minX..maxX]
return board
applyCommand board (Vertical (minY, maxY) x) = do
mapM_ (\y -> writeArray board (y, x) Clay) [minY..maxY]
return board
in do
initial <- MA.newArray (extendXBy 1 bounds) Sand
foldM applyCommand initial commands

findMinY :: [InputCommand] -> Int
findMinY commands =
let getY c = case commandBounds c of
((minY, _), _) -> minY

go !mY [] = mY
go !mY (c:cs) =
let mY' = if mY < getY c then mY else getY c
in go mY' cs
in go (getY $ head commands) $ tail commands

flowWaterOneTick :: Board s -> [(Int, Int)] -> ST s [(Int, Int)]
flowWaterOneTick _ [] = return []
flowWaterOneTick board (p:ps) = do
(_, (maxY, _)) <- MA.getBounds board
let extendDown (!y, !x) = do
belowCell <- readArray board (y+1, x)
case belowCell of
Sand -> do writeArray board (y+1, x) MovingWater
return [(y+1, x)]
Clay -> extendSideways (y, x)
MovingWater -> return []
StillWater -> extendSideways (y, x)

boundedOn dir (!y, !x) = do
belowCell <- readArray board (y+1, x)
if flowAbove belowCell
then do dirCell <- readArray board (y, dir x)
case dirCell of
Sand -> boundedOn dir (y, dir x)
Clay -> return True
StillWater -> return True
MovingWater -> boundedOn dir (y, dir x)
else return False

boundedOnBothSides (y, x) =
boundedOn (subtract 1) (y, x) <&&> boundedOn (+1) (y, x)

extendTo dir as (!y, !x) = do
belowCell <- readArray board (y+1, x)
let fillAndContinue =
do writeArray board (y, x) as
dirCell <- readArray board (y, dir x)
case dirCell of
Sand -> extendTo dir as (y, dir x)
Clay -> return Nothing
MovingWater -> extendTo dir as (y, dir x)
StillWater -> return Nothing

fillAndExtend =
do writeArray board (y, x) as
return $ Just (y, x)

case belowCell of
Sand -> fillAndExtend
Clay -> fillAndContinue
MovingWater -> return Nothing
StillWater -> fillAndContinue

extendSideways (!y, !x) = do
isBounded <- boundedOnBothSides (y, x)
if isBounded
then do _ <- extendTo (subtract 1) StillWater (y, x)
_ <- extendTo (+1) StillWater (y, x)
return [(y-1, x)]
else do left <- extendTo (subtract 1) MovingWater (y, x)
right <- extendTo (+1) MovingWater (y, x)
return $ catMaybes [left, right]

if fst p == maxY
then return ps
else do -- boardText <- showBoard board
-- traceM "---------"
-- traceM $ show (p:ps)
-- bounds <- MA.getBounds board
-- traceM $ show bounds
-- traceM boardText
ps' <- extendDown p
return $ ps' ++ ps

flowWater :: Board s -> [(Int, Int)] -> ST s ()
flowWater _ [] = return ()
flowWater board ps = do
ps' <- flowWaterOneTick board ps
flowWater board ps'

countCells :: Board s -> Int -> (BoardCell -> Bool) -> ST s Int
countCells board minY target =
length
. filter target
. map snd
. filter ((>= minY) . fst . fst)
<$> MA.getAssocs board

main :: IO ()
main = do
args <- getArgs
case args of
[] -> run stdin
file:_ ->
withFile file ReadMode run

run :: Handle -> IO ()
run inputFile = do
input <- hGetContents inputFile
case parse inputParser "<input>" input of
Left errorText -> print errorText
Right commands -> do
let isWater = \case MovingWater -> True
StillWater -> True
_ -> False
isStillWater = \case StillWater -> True
_ -> False
let (solution1, solution2) = runST $ do
board <- buildBoard commands
flowWater board [(0, 500)]
res1 <- countCells board (findMinY commands) isWater
res2 <- countCells board (findMinY commands) isStillWater
return (res1, res2)
print solution1
print solution2
64 changes: 64 additions & 0 deletions day17/stack.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# This file was automatically generated by 'stack init'
#
# Some commonly used options have been documented as comments in this file.
# For advanced use and comprehensive documentation of the format, please see:
# https://docs.haskellstack.org/en/stable/yaml_configuration/

# Resolver to choose a 'specific' stackage snapshot or a compiler version.
# A snapshot resolver dictates the compiler version and the set of packages
# to be used for project dependencies. For example:
#
# resolver: lts-3.5
# resolver: nightly-2015-09-21
# resolver: ghc-7.10.2
#
# The location of a snapshot can be provided as a file or url. Stack assumes
# a snapshot provided as a file might change, whereas a url resource does not.
#
# resolver: ./custom-snapshot.yaml
# resolver: https://example.com/snapshots/2018-01-01.yaml
resolver: lts-13.1

# User packages to be built.
# Various formats can be used as shown in the example below.
#
# packages:
# - some-directory
# - https://example.com/foo/bar/baz-0.0.2.tar.gz
# - location:
# git: https://github.com/commercialhaskell/stack.git
# commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a
# - location: https://github.com/commercialhaskell/stack/commit/e7b331f14bcffb8367cd58fbfc8b40ec7642100a
# subdirs:
# - auto-update
# - wai
packages:
- .
# Dependency packages to be pulled from upstream that are not in the resolver
# using the same syntax as the packages field.
# (e.g., acme-missiles-0.3)
# extra-deps: []

# Override default flag values for local packages and extra-deps
# flags: {}

# Extra package databases containing global packages
# extra-package-dbs: []

# Control whether we use the GHC we find on the path
# system-ghc: true
#
# Require a specific version of stack, using version ranges
# require-stack-version: -any # Default
# require-stack-version: ">=1.9"
#
# Override the architecture used by stack, especially useful on Windows
# arch: i386
# arch: x86_64
#
# Extra directories used by stack for building
# extra-include-dirs: [/path/to/dir]
# extra-lib-dirs: [/path/to/dir]
#
# Allow a newer minor version of GHC than the snapshot specifies
# compiler-check: newer-minor

0 comments on commit 1888245

Please sign in to comment.