Day 3: Squares With Three Sides


In [1]:
inputLines = lines <$> readFile "input/day3.txt"

In [2]:
-- Parse a string that contains space-separated numbers
parseNumbers :: String -> [Int]
parseNumbers = map read . words

In [3]:
import Data.List -- for sort

In [4]:
isValidTriangle :: [Int] -> Bool
isValidTriangle (a:b:c:[]) = head sortedSides < sum (tail sortedSides)
    where
        sortedSides = reverse $ sort [a, b, c]
isValidTriangle _ = False  -- too many or too few sides

Part 1: every input row contains the sides of a triangle


In [5]:
length . filter isValidTriangle . map parseNumbers <$> inputLines


869

Part 2: a column in three consecutive rows contains the sides of a triangle

Idea:

  • verify that the number of rows is divisible by 3
  • use transpose to put all numbers in a column into a list
  • concatenate the columms with concat
  • split the list into sublists of length 3 with splitEvery

In [6]:
-- the number of lines is divisible by 3 if the remainder is zero
(`mod` 3) . length <$> inputLines


0

In [7]:
import Data.List.Split -- for splitEvery

In [8]:
length . filter isValidTriangle . splitEvery 3 . concat . transpose . map parseNumbers <$> inputLines


1544