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:
c("hoppity").
Run the code in the Erlang shell:
hoppity:start().
-module(hoppity).
-export([start/0]).
start() ->
{ok, Device} = file:open("/home/rick/Programming/Hoppity_Hop/data.txt",[read]),
ALine = string:strip(getALine(Device)),
{AsInt, Junk} = string:to_integer(ALine),
printHoppity(AsInt),
io:fwrite("~n~s", [" "]).
getALine(Device) ->
case io:get_line(Device, "") of
eof -> file:close(Device), "None";
Line -> file:close(Device), Line
end.
printHoppity(Num) ->
printHoppityNTimes(1, Num).
printHoppityNTimes(Current, Max) ->
if Current > Max ->
pass;
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)
end.
printHoppityValue(0, 0) ->
io:fwrite("~n~s", ["Hop"]);
printHoppityValue(0, _) ->
io:fwrite("~n~s", ["Hoppity"]);
printHoppityValue(_, 0) ->
io:fwrite("~n~s", ["Hophop"]);
printHoppityValue(_,_) ->
pass.
No comments:
Post a Comment