module Problem102 where

import Data.List.Split

main :: IO ()
main =
    readFile "txt/102.txt"
        >>= print
        .   length
        .   filter containsOrigin
        .   map (map read . wordsBy (== ','))
        .   lines

containsOrigin :: [Double] -> Bool
-- line through two points should have origin and the other point on same side
-- (x1,y1) - (x2,y2) => (y-y2)/(y2-y1) = (x-x2)/(x2-x1)
-- or (y-y2) - [(y2-y1)/(x2-x1)](x-x2) = 0
-- for (x3,y3) -> (y3-y2) - [(y2-y1)/(x2-x1)](x3-x2) = (-y2)-[(y2-y1)/(x2-x1)](-x2)
containsOrigin [x1, y1, x2, y2, x3, y3] =
    sameSide (x1, y1) (x2, y2) (x3, y3) (0, 0)
        && sameSide (x1, y1) (x3, y3) (x2, y2) (0, 0)
        && sameSide (x2, y2) (x3, y3) (x1, y1) (0, 0)

sameSide
    :: (Double, Double)
    -> (Double, Double)
    -> (Double, Double)
    -> (Double, Double)
    -> Bool
sameSide (x1, y1) (x2, y2) (x3, y3) (x4, y4) = signum (r (x3, y3)) == signum (r (x4, y4))
  where
    m = (y2 - y1) / (x2 - x1)
    r (a, b) = (b - y2) - m * (a - x2)
