Last active
June 6, 2021 11:52
-
-
Save shritesh/b17977389959b04308627616e839ae02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule End do | |
defmodule Region do | |
defstruct name: "", population: 0, south_edge: 0 | |
end | |
defp tally(lines, regions) do | |
Enum.reduce(lines, regions, fn line, regions -> | |
fields = String.split(line, "\t") | |
{latitude, _} = Enum.at(fields, 4) |> Float.parse() | |
{population, _} = Enum.at(fields, 14) |> Integer.parse() | |
{regions, _found?} = | |
Enum.map_reduce(regions, false, fn | |
region, false when latitude >= region.south_edge -> | |
{%{region | population: region.population + population}, true} | |
region, found? -> | |
{region, found?} | |
end) | |
regions | |
end) | |
end | |
def main do | |
regions = [ | |
%Region{name: "North", south_edge: 0}, | |
%Region{name: "South", south_edge: -90} | |
] | |
[filename] = System.argv() | |
File.stream!(filename) | |
|> tally(regions) | |
|> Enum.each(&IO.puts("#{&1.name}: #{&1.population}")) | |
end | |
end | |
End.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment