~statianzo/sevenlangs

ref: 6fcdf67ba6b46203ad445e4b43a50edec596331e sevenlangs/erlang/aoc/src/aoc01.erl -rw-r--r-- 852 bytes
6fcdf67bJason Staten advent of code challenges 1 year, 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
-module(aoc01).

-export([calculate_module/1, fuel/2, run/0, run2/0]).

all_lines(Path) ->
    {ok, Fd} = file:open(Path, read),
    Lines = all_lines(Fd, []),
    file:close(Fd),
    lists:reverse(Lines).

all_lines(Fd, Lines) ->
    case file:read_line(Fd) of
      {ok, Line} ->
	  all_lines(Fd, [string:chomp(Line) | Lines]);
      eof -> Lines
    end.

calculate_module(Mass) -> math:floor(Mass / 3) - 2.

fuel(Mass, Total) when Mass =< 6 -> Total;
fuel(Mass, Total) -> 
  Fuel = math:floor(Mass / 3) - 2,
  fuel(Fuel, Total + Fuel).

run() ->
    Lines = all_lines("aoc01.txt"),
    FuelQuantities = [calculate_module(list_to_integer(X))
		      || X <- Lines],
    lists:sum(FuelQuantities).

run2() ->
    Lines = all_lines("aoc01.txt"),
    FuelQuantities = [fuel(list_to_integer(X), 0)
		      || X <- Lines],
    lists:sum(FuelQuantities).