Home Posts Tags Post Search Tag Search

Post 26

Hacker Rank 02 - Area of a Polynomial

Published on: 2025-05-15 Tags: elixir, Blog, Hacker Rank
So for this one I needed to find the area of a polynomial where I only know the points (x, y) and the number of points. I can also assume that the points don't go through each other. 

So for this one I had to parse the input:
def read do
    number_of_points =
        IO.read(:stdio, :line)
        |> String.trim()
        |> String.integer()

    points = Enum.map(0..number_of_points - 1, fn _ ->
         IO.read(:stdio, :line)
        |> String.trim()
        |> String.replace("\n", "")
        |> String.split(" ")
        |> Enum.map(&String.integer(1&))
    end)
    points ++ [List.first(points)]
end

Okay so before I go over this I want to talk about the fact that the cross product of all the points on a polynomial. So its every 2 points cross product so you need to go all the way around and then back to the first point.

So basically you have the number of points (first line)
Then the points in order.

Now with this I need to use chunk_by in order to hit each set of pairs. 

Enum.chunk_every(list, 2, 1, :discard)

This will grab 2 elements and then move the index by 1 so they overlap.

Once I have the ordered pairs I need to take the cross product of every element

Enum.map(pairs, fn [[x1, y1], [x2, y2]] -> 
    x1 * y2 - x2 * y1
end)

Next we sum those elements

|> Enum.sum()

Take the Absolute Values

|> abs()

Then I created a helper function for taking have the value

|> half()

Boom output and you are done.