Saturday, December 12, 2009

Erlang solution for the Hoppity problem

The latest in the Code Snippets series.

An Erlang solution to the Hoppity problem.

For those who have never tried functional programming, here's a taste of what you might encounter. For those who know how to program in this way, I salute you! I did much learning on the way, there is much more road to travel.

To run the code:
Put the code in a file called hoppity.erl.
In the Erlang shell ('erl'), compile the file by typing:

Run the code in the Erlang shell:


start() ->
{ok, Device} = file:open("/home/rick/Programming/Hoppity_Hop/data.txt",[read]),
ALine = string:strip(getALine(Device)),
{AsInt, Junk} = string:to_integer(ALine),
io:fwrite("~n~s", [" "]).

getALine(Device) ->
case io:get_line(Device, "") of
eof -> file:close(Device), "None";
Line -> file:close(Device), Line

printHoppity(Num) ->
printHoppityNTimes(1, Num).

printHoppityNTimes(Current, Max) ->
if Current > Max ->
true -> % 'else'
ByThree = Current rem 3,
ByFive = Current rem 5,
%io:fwrite("~n~s", [integer_to_list(ByThree)]),
%io:fwrite("~n~s", [integer_to_list(ByFive)]),
printHoppityValue(ByThree, ByFive),
printHoppityNTimes(Current + 1, Max)

printHoppityValue(0, 0) ->
io:fwrite("~n~s", ["Hop"]);
printHoppityValue(0, _) ->
io:fwrite("~n~s", ["Hoppity"]);
printHoppityValue(_, 0) ->
io:fwrite("~n~s", ["Hophop"]);
printHoppityValue(_,_) ->

No comments: