Carrying on from Cedric’s Challenge (C#, Erlang) I decided to do some of the Programming Challenges problems in Erlang, because the problems are small, but fun.
My first is Reverse And Add #110502 and here is my solution:
-module(revandadd). -export([rev_and_add/1, test/0]).%% number to list ntl(Num) -> ntl(Num, []). ntl(0, List) -> List; ntl(Num, List) -> ntl(Num div 10, [Num rem 10]++List). %% list to number ltn(List) -> ltn(List, 0). ltn([], Num) -> Num; ltn([H|T], Num) -> ltn(T, (Num*10)+H). %% is palindrome is_pal(Num) -> ntl(Num) == lists:reverse(ntl(Num)). rev_and_add(Num) -> rev_and_add(Num, 1). rev_and_add(Num, Count) -> Pal = ltn(lists:reverse(ntl(Num))) + Num, case is_pal(Pal) of true -> [Count,Pal]; false -> rev_and_add(Pal, Count+1) end. test() -> [4,9339] = rev_and_add(195), [5,45254] = rev_and_add(265), [3,6666] = rev_and_add(750), true.
I’m not too happy with the number-to-list functions as I’m sure there should be a built in way to-do this already, which Joe implies therefore there probably is.
You’re looking for integer_to_list(Integer) and list_to_integer(List), they’re built-in functions (often referred to as “BIFs”) and usable just like that (no module).
They’re actually part of the “erlang” module http://www.erlang.org/doc/man/erlang.html
which is a bit confusing, because most (but not all!) of the functions in that module can be used without specifying “erlang:” in front of the name.
Thank you so much Tobias, I will now go read that section, so I’m more informed from now on…
integer_to_list(Integer) and list_to_integer(List) make a list of the text digits, where-as I was using just a list of the digits in numerical value, but as I’m just reversing and comparing, those functions will do.
[...] Simeon Pilgrim Not just another WordPress weblog « Reverse And Add 110502 in Erlang [...]