Last active
August 29, 2015 13:56
-
-
Save l0gicpath/8987472 to your computer and use it in GitHub Desktop.
Project Euler problem #4 solution in Erlang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(problem_4). | |
-export([solve/0]). | |
solve() -> | |
List = lists:seq(100, 999), | |
[H | L] = [X * Y || X <- List, | |
Y <- List, | |
integer_to_list(X * Y) =:= lists:reverse(integer_to_list(X * Y))], | |
solve(L, H). | |
solve([], Largest) -> Largest; | |
solve([H | L], Largest) when H > Largest -> solve(L, H); | |
solve([_ | L], Largest) -> solve(L, Largest). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
solve/0 kicks off generating a list of all 3-digit numbers
Then using list comprehension, we filter that list to find all the palindromes in that range
What this really does is, returning the X * Y for which X and Y are a list all 3-digit numbers and their product is a palindrome number. To test for that we first convert the number to a string which we then compare it with the reverse of itself.
Thus, eventually forming a filtered list of all the palindromes in that range [100...999].
On the same line, we are using Erlang's pattern matching, extracting the first element of the palindromes list to use as our initial candidate for the largest palindrome number.
Finally solve/2 kicks off taking the palindromes list and the largest candidate, this is recursion so our base case is if the palindromes list is empty which means we've either found no palindromes earlier in solve/0 or finished going through the list, then we'll exit the recursion returning the largest candidate so far.
Next guard will replace the current largest candidate with the first palindrome on the current palindrome list if the first element is larger than the current candidate.