-module(fastbeust). -export([challenge/1]). challenge(Max) -> statistics(wall_clock), Listener = spawn(fun() -> listen() end), Digits = new_digits(), find_loop(1, 10, Digits, Max, Listener), {_, Elapsed} = statistics(wall_clock), io:format("~p ms elapsed to complete count to ~p~n", [Elapsed, Max]). find_loop(N, NMax, _Digits, _Max, _Listener) when N > NMax -> done; find_loop(N, NMax, Digits, Max, Listener) -> {_Zero, One} = gb_sets:next(gb_sets:iterator(Digits)), case find(One, Digits, N, 0, Max, Listener) of done -> done; _ -> find_loop(N+1, NMax, Digits, Max, Listener) end. find(none, _, _, _, _, _) -> continue; find(Current, Digits, Remaining, Value, Max, Listener) -> case gb_sets:next(Current) of none -> continue; {CurrentValue, Next} -> NewValue = Value + CurrentValue, case Remaining of 1 -> if NewValue > Max -> done; true -> Listener ! NewValue, find(Next, Digits, Remaining, Value, Max, Listener) end; _ -> NewDigits = gb_sets:delete(CurrentValue, Digits), case find(gb_sets:iterator(NewDigits), NewDigits, Remaining - 1, NewValue * 10, Max, Listener) of done -> done; _ -> find(Next, Digits, Remaining, Value, Max, Listener) end end end. new_digits() -> gb_sets:from_list(lists:seq(0,9)). listen() -> receive Num -> %%io:fwrite("~p~n", [Num]), listen() end.