|
| 1 | +-module(solution2). |
| 2 | +-export([main/0]). |
| 3 | + |
| 4 | +main() -> start([]). |
| 5 | + |
| 6 | +start(Total) -> |
| 7 | + case io:get_line("") of |
| 8 | + eof -> |
| 9 | + io:format("~p~n", [complete(lists:map(fun(X) -> [1, X] end, Total), 0)]); |
| 10 | + |
| 11 | + Input -> |
| 12 | + [Cnt, _] = solve(string:trim(Input)), |
| 13 | + start(Total ++ [Cnt]) |
| 14 | + end. |
| 15 | + |
| 16 | +solve(Input) -> |
| 17 | + [_, Right] = lists:map(fun string:trim/1, string:split(Input, ":")), |
| 18 | + [Lookup, Rest] = lists:map(fun splitNumber/1, lists:map(fun string:trim/1, string:split(Right, " | "))), |
| 19 | + LookupSet = sets:from_list(Lookup), |
| 20 | + Count = operate(LookupSet, Rest, 0), |
| 21 | + [Count, Rest]. |
| 22 | + |
| 23 | + |
| 24 | +splitNumber(Input) -> lists:map(fun(X) -> {Int, _} = string:to_integer(X), Int end, re:split(Input, "\s+")). |
| 25 | + |
| 26 | + |
| 27 | +operate(_, [], Value) -> Value; |
| 28 | +operate(Set, [Fst | Rst], Value) -> |
| 29 | + State = sets:is_element(Fst, Set), |
| 30 | + if |
| 31 | + State -> operate(Set, Rst, Value + 1); |
| 32 | + true -> operate(Set, Rst, Value) |
| 33 | + end. |
| 34 | + |
| 35 | + |
| 36 | +complete([], Val) -> Val; |
| 37 | +complete([[Cnt, _]], Val) -> Val + Cnt; |
| 38 | +complete([[Cnt, Itr] | Rst], Val) -> |
| 39 | + Value = sumAdd(Rst, Itr, Cnt), |
| 40 | + complete(Value, Val + Cnt). |
| 41 | + |
| 42 | + |
| 43 | +sumAdd(Array, Count, Add) -> |
| 44 | + case Count of |
| 45 | + 0 -> Array; |
| 46 | + _Else -> |
| 47 | + [[Ctr, El] | Rst] = Array, |
| 48 | + [[Ctr + Add, El]] ++ sumAdd(Rst, Count - 1, Add) |
| 49 | + end. |
0 commit comments