Files
brc/brc.exs

53 lines
1.2 KiB
Elixir
Raw Permalink Normal View History

2024-01-17 15:00:57 +01:00
Mix.install([
2024-01-17 15:51:25 +01:00
{:flow, "~> 1.2.4"},
{:ex_cldr_collation, "~> 0.7.2"}
2024-01-17 15:00:57 +01:00
])
defmodule Brc do
2024-01-17 15:51:25 +01:00
require Logger
2024-01-17 15:00:57 +01:00
def run(path) do
2024-01-17 17:10:45 +01:00
compute_file(path)
|> output_results()
2024-01-17 15:00:57 +01:00
end
2024-01-17 17:10:45 +01:00
def compute_file(path) do
Logger.info("computing from file #{path}")
2024-01-17 15:00:57 +01:00
2024-01-17 15:51:25 +01:00
File.stream!(path)
|> Flow.from_enumerable()
|> Flow.map(&parse_line/1)
2024-01-17 17:10:45 +01:00
|> Flow.partition(key: {:elem, 0})
|> Flow.reduce(fn -> %{} end, &update_city_temp_map/2)
end
def update_city_temp_map({city, temp}, acc) do
Map.update(acc, city, [temp, temp, temp],
fn [prev_min, prev_max, mean] ->
[
min(prev_min, temp),
max(prev_max, temp),
(mean + temp) / 2
]
2024-01-17 15:00:57 +01:00
end)
end
def parse_line(line) do
2024-01-17 17:10:45 +01:00
[city, temp_text] = String.trim(line) |> String.split(";")
{city, String.to_float(temp_text)}
end
def output_results(results) do
for {city, [min, max, mean]} <- results do
"#{city}=#{min}/#{max}/#{Float.round(mean, 1)}"
end
|> Enum.sort(Cldr.Collation)
|> Enum.join(",")
|> then(fn out -> "{" <> out <> "}" end)
|> IO.puts()
2024-01-17 15:00:57 +01:00
end
end
2024-01-17 17:10:45 +01:00
{path, _} = System.argv() |> List.pop_at(0, "./measurements.txt")
Brc.run(path)