finish day four

This commit is contained in:
qvalentin 2022-12-11 14:25:56 +01:00
parent 2fc2e7351e
commit 155f405189
Signed by: qvalentin
GPG Key ID: C979FA1EAFCABF1C
3 changed files with 84 additions and 0 deletions

31
four-easy.hs Normal file
View File

@ -0,0 +1,31 @@
import Control.Monad
import Data.Char
parseLine :: String -> [[Int]]
parseLine line = [parseAssignment $ takeWhile (/= ',') line,
parseAssignment $ drop 1 $ dropWhile (',' /= ) line]
parseAssignment :: String -> [Int]
parseAssignment assignment = do
let first = takeWhile ('-' /=) assignment
let second = drop 1 $ dropWhile ('-' /=) assignment
[(read first).. (read second)]
isIncludedElseWhere :: [[Int]] -> [Int] -> [[Int]] -> Int -> Int
isIncludedElseWhere previous current [] count=count
isIncludedElseWhere previous current next count=do
let found = (isIncluded current previous && isIncluded current next)
(if found then 1 else 0) +
(isIncludedElseWhere (current:previous) (head next) (tail next) count)
isIncluded :: [Int] -> [[Int]] -> Bool
isIncluded current list = any includes list
where
includes :: [Int] -> Bool
includes range' = all (`elem` range') current
main = do
input <- readFile "four-input2.txt"
let lists= ( join $ map (parseLine) $ lines input)
print $ isIncludedElseWhere [] (head lists) (tail lists) 0

28
four.hs Normal file
View File

@ -0,0 +1,28 @@
import Control.Monad
import Data.Char
parseLine :: String -> [[Int]]
parseLine line = [parseAssignment $ takeWhile (/= ',') line,
parseAssignment $ drop 1 $ dropWhile (',' /= ) line]
parseAssignment :: String -> [Int]
parseAssignment assignment = do
let first = takeWhile ('-' /=) assignment
let second = drop 1 $ dropWhile ('-' /=) assignment
[(read first).. (read second)]
isIncluded :: [Int] -> [[Int]] -> Bool
isIncluded current list = any includes list
where
includes :: [Int] -> Bool
includes range' = all (`elem` range') current
coveredByPartner :: [[Int]] -> Bool
coveredByPartner [first,second] = isIncluded first [second] || isIncluded second [first]
main = do
input <- readFile "four-input.txt"
let lists= (map (parseLine) $ lines input)
print $ length $ filter id $ map coveredByPartner lists

25
four2.hs Normal file
View File

@ -0,0 +1,25 @@
import Control.Monad
import Data.Char
import Data.List
parseLine :: String -> [[Int]]
parseLine line = [parseAssignment $ takeWhile (/= ',') line,
parseAssignment $ drop 1 $ dropWhile (',' /= ) line]
parseAssignment :: String -> [Int]
parseAssignment assignment = do
let first = takeWhile ('-' /=) assignment
let second = drop 1 $ dropWhile ('-' /=) assignment
[(read first).. (read second)]
coveredByPartner :: [[Int]] -> Bool
coveredByPartner [first,second] = 0 /= (length $ intersect first second)
main = do
input <- readFile "four-input.txt"
let lists= (map (parseLine) $ lines input)
print $ length $ filter id $ map coveredByPartner lists