My first Erlang program, all on my own
[well, with a lot of time spent on the online doc…]. It’s the classic Coconuts problem, which you can find described here:
This problem, which appeared in a short story by Ben Ames Williams, concerns five men on a deserted island who gather a pile of coconuts. During the night, one of the men wakes up and decides to take his share in advance. He divides the coconuts into five equal piles. One coconut is left over, and he tosses it to a nearby monkey. Hiding his pile and consolidating the four remaining piles, he returns to sleep.
The second man does the same thing, dividing the now slightly smaller pile into five equal ones, tossing the one leftover coconut to the monkey, hiding his pile and returning to sleep. The third, fourth and fifth man all repeat the same pattern.
When all awake in the morning, the pile looks smaller, but each man is as guilty as the others, so no one says anything. They divide the remaining coconuts into five equal piles as the monkey watches. This time, though, there are no coconuts left over.
How many coconuts did they start with?
The code below can probably be cleaned up, improved, yadada, but it gives the right answer…
-module(coconuts).
-export([start/0]).
start() ->
doWork(5,1,5).
doWork(99999,1,99999) ->
done;
doWork(Orig, 6, Temp) ->
if
(Temp rem 5) == 0 ->
io:format("Victory! ~w~n",[Orig]);
Temp rem 5 /= 0 ->
doWork(Orig+1, 1, Orig+1),
done
end;
doWork(Orig, Man, Temp) ->
if
(Temp rem 5) /= 1 ->
doWork(Orig+1, 1, Orig+1);
(Temp rem 5) == 1 ->
doWork(Orig, Man + 1, trunc((Temp-1)*4/5))
end.
Execution:
104> c(coconuts).
{ok,coconuts}
105> coconuts:start().
Victory! 3121
ok
This is mind-boggling. I sat at my desk tonight with the goal of writing a small program and understand how it worked. Using recursion instead of loops makes my head splinter in multiple places. Basically you test and redirect the flow with overloading of a function [testing for 99,999 thousand iterations on the pile, for 6 iterations on Man, etc…], and this makes me feel like throwing a for-next loop at the screen. But, OK, it works, it’s fast, and I have decided to learn Erlang, so I’ll get on with the program…
/me shakes fist at the Erlang people for writing half-assed docs…
Erlang