Day 4: Secure Container

https://adventofcode.com/2019/day/4


In [1]:
inputLine = head . lines <$> readFile "input/day04.txt"

In [2]:
import Data.List.Split
import Control.Monad

In [3]:
minAndMaxValues = map read . splitOn "-" <$> inputLine

Part 1

A valid password

  • consists of 6 digits
  • the digits never decrease going from left to right
  • two adjacent digits are the same
  • the value is in the range given by the puzzle input

In [4]:
hasSameAdjacentDigits :: [Int] -> Bool
hasSameAdjacentDigits = any (uncurry (==)) . (zip <*> tail)

In [5]:
validPasswords constraint [minValue, maxValue] = do
    a <- [0..9]
    b <- [a..9]
    c <- [b..9]
    d <- [c..9]
    e <- [d..9]
    f <- [e..9]
    let digits = [a, b, c, d, e, f]
    guard $ constraint digits
    let password = passwordFromDigits digits
    guard $ minValue <= password && password <= maxValue
    return password

    where
        passwordFromDigits :: [Int] -> Int
        passwordFromDigits = foldl1 ((+) . (10*))

In [6]:
length . validPasswords hasSameAdjacentDigits <$> minAndMaxValues


1610

Part 2

Part 2 has the additional constraint that the password needs at least one group of exactly two subsequent equal digits.


In [7]:
import Data.List

In [8]:
hasGroupOf2 :: [Int] -> Bool
hasGroupOf2 = elem 2 . map length . group

In [9]:
length . validPasswords hasGroupOf2 <$> minAndMaxValues


1104