%% to compile: erlc day3A.erl
%% to run: erl -noshell -s day5 solve
%%
-module(day7).

-export ([solve/0, solve/1, solve/2]).
-export ([read_input/0]).

solve() ->
    solve(['1']),
    solve(['2']),
    init:stop().

solve(A) ->
    solve(A, read_input()).

solve(['1'], D) ->
    io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
solve(1, D) ->
    solution1(D);
solve(['2'], D) ->
    io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
solve(2, D) ->
    solution2(D).

read_input() ->
    {ok, IO} = file:open("input.txt", 'read'),
    Data = read_input(IO),
    file:close(IO),
    Data.

read_input(IO) ->
    read_line(IO).

read_line(IO) ->
    case file:read_line(IO) of
        'eof' -> 'eof';
        {ok, Line} -> parse_line(Line)
    end.

parse_line(Line) ->
    Points = string:tokens(Line, " ,->\n"),
    [list_to_integer(X) || X <- Points].

solution1(Input) ->
    Max = lists:max(Input),
    Min = lists:min(Input),
    io:format("Max: ~p Min: ~p~n", [Max, Min]),
    Fuels = [ fuel_needed(X, Input, fun fuel1/2) || X <- lists:seq(Min, Max)],
    lists:min(Fuels).

solution2(Input) ->
    Max = lists:max(Input),
    Min = lists:min(Input),
    io:format("Soln2: Max: ~p Min: ~p~n", [Max, Min]),
    Fuels = [ fuel_needed(X, Input, fun fuel2/2) || X <- lists:seq(Min, Max)],
    lists:min(Fuels).

fuel_needed(Pos, Data, Fuel_fun) ->
	fuel_needed(Pos, Data, Fuel_fun, 0).

fuel_needed(_Pos, [], _, Acc) -> Acc;
fuel_needed(Pos, [H|T], Fuel_fun, Acc) ->
	fuel_needed(Pos, T, Fuel_fun, Acc + Fuel_fun(H, Pos)).

fuel1(X, X) -> 0;
fuel1(X, Y) when X > Y -> X - Y;
fuel1(X, Y) when Y > X -> Y - X.

fuel2(X, X) -> 0;
fuel2(X, Y) when X > Y -> fuel_steps(X - Y);
fuel2(X, Y) when Y > X -> fuel_steps(Y - X).

fuel_steps(X) ->
	fuel_steps(X, 1, 0).

fuel_steps(0, _Cost, Count) -> Count;
fuel_steps(X, Cost, Count) ->
	fuel_steps(X - 1, Cost + 1, Count + Cost).
