···11+## Day 9
22+33+This day's problem is based on simple coordinate geometry.
44+55+Parse the input data first (pairs of numbers separated by commas, one pair per line):
66+77+```haskell
88+import Data.List.Split (splitOn)
99+1010+parse :: String -> [[Integer]]
1111+parse = map (map read . splitOn ",") . lines
1212+```
1313+1414+Onto the problem itself.
1515+1616+### Part 1
1717+1818+This part requires us to simply find a rectangle with the largest area among the points given to us, so first write a method to compute areas given a point. Remember that our representation of a point is `[x, y]`:
1919+2020+```haskell
2121+area :: [Integer] -> [Integer] -> Integer
2222+area [x, y] [x', y'] =
2323+ (1 + abs (x - x')) * (1 + abs (y - y'))
2424+```
2525+2626+Thus, the solution to the first part is given by the following list comprehension:
2727+2828+```haskell
2929+p1 :: [[Integer]] -> Integer
3030+p1 poly = maximum [area p p' | p <- poly, p' <- poly]
3131+```
3232+3333+### Part 2
3434+3535+This part is a whole lot trickier. We now require only rectangles that fall *within* the polygon. Rectangles that have areas outside the polygon should be ignored. The methodology here is to identify rectangles that do not intersect in any way with the polygon itself. Sharing an edge with the polygon is alright however.
3636+3737+Luckily, the intersections are quite easily calculated, since all lines of the polygon are oriented along the axes, and so are the lines forming the rectangle. If a line of the polygon falls to the left of the leftmost line of the rectangle, or to the right of the rightmost line, or above the topmost line, or below the bottommost line, then the line does not intersect the rectangle:
3838+3939+```haskell
4040+intersects :: [Integer] -> [Integer] -> [[Integer]] -> Bool
4141+intersects [x, y] [x', y'] = not . all away . pairs
4242+ where
4343+ pairs (p : ps) = zip (p : ps) (ps ++ [p])
4444+ away ([lx, ly], [lx', ly']) =
4545+ (max lx lx' <= min x x')
4646+ || (min lx lx' >= max x x')
4747+ || (max ly ly' <= min y y')
4848+ || (min ly ly' >= max y y')
4949+```
5050+5151+To explain a bit further, we define `away` according the the rules above. Then the `intersects` method is given by simply ensuring that of all pairs of points in the polygon (we need pairs to compute line segments of the polygon), we have atleast one line segment that is not away from the rectangle.
5252+5353+Thus, the solution to the second part is a similar list comprehension with an additional guard:
5454+5555+```haskell
5656+p2 :: [[Integer]] -> Integer
5757+p2 poly =
5858+ maximum
5959+ [ area p p'
6060+ | p <- poly,
6161+ p' <- poly,
6262+ not (intersects p p' poly)
6363+ ]
6464+```
6565+6666+Finally, a main function to wrap it all up:
6767+6868+```haskell
6969+main = do
7070+ n <- parse <$> getContents
7171+ print $ p1 n
7272+ print $ p2 n
7373+```