writeString = case File.read("../letters.txt") do
{:ok, body} -> body
{:error, _reason} -> IO.puts("failed to get file")
end
|> String.split(" ", trim: true)
|> Enum.reduce(Map.new(), fn code, acc -> case Map.has_key?(acc, String.to_integer(code)) do
false -> Map.put(acc, String.to_integer(code), 1)
true -> {_old, newMap} = Map.get_and_update!(acc, String.to_integer(code), fn current_value ->
{current_value, current_value + 1}
end)
newMap
end
end)
|> Enum.sort_by(fn {k,v} -> {v,k} end, :desc)
|> Enum.reduce("", fn {k, v}, acc -> acc <> Integer.to_string(k) <> ": " <> Integer.to_string(v) <> "\n" end)
{:ok, file} = File.open("output.txt", [:write])
IO.binwrite(file, writeString)
Do you have any idea how many letters Santa gets each year before Christmas? Millions of people around the world send letters to Santa every year letting him know what they would like for Christmas. However, the logistics of not only reading those letters, but estimating labor, ordering materials, storing products, and loading up presents at the appropriate time in an efficient order requires a lot of planning.
Problem: In order to prepare for this Christmas season, some of the head elves would like a report on how many letters are coming from each country. The elves physically receiving the letters have been inputting the country code of the letter into a file named letters.txt. You need to read this file, and then report how many letters have been sent from each country.
Challenge: A letters_challenge.txt has also been included if you’d like some extra credit. There is a lot more data in this file, so it may need to be handled a bit differently so as not to overload your memory. (Note: github has limitations on file size. Feel free to use the python script to make a larger file).
Example:
Input:
1 2 34 53 1 53 6
Output:
1: 2
2: 1
6: 1
34: 1
53: 2