Created
May 8, 2020 16:59
-
-
Save gorkaio/be5494030605e0d5992638afd7bfc041 to your computer and use it in GitHub Desktop.
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(palindrome). | |
-export([palindrome/1,normalize/1]). | |
-export([palindrome_test/0,normalize_test/0]). | |
%% Palindrome %%% | |
palindrome([]) -> false; | |
palindrome(S) -> | |
Sn = normalize(S), | |
palindrome(Sn,lists:reverse(Sn), false). | |
palindrome([],[],Ac) -> Ac; | |
palindrome([H1|T1], [H2|T2],_) when H1==H2 -> | |
palindrome(T1,T2,true); | |
palindrome(_,_,_) -> false. | |
palindrome_test() -> | |
false = palindrome(""), | |
false = palindrome(" \t\n"), | |
true = palindrome("A"), | |
true = palindrome("Madam I\'m Adam"), | |
false = palindrome("Not a palindrome!"), | |
passed. | |
%% Normalize strings %%% | |
% Remove anything not alphanumerical and convert to lowercase | |
normalize(S) -> | |
Sn = re:replace(S, "[[:^alpha:]]", "", [global,{return, list}]), | |
string:to_lower(Sn). | |
normalize_test() -> | |
"crazylittlething" = normalize(" ~~ CRaZY LiTTLe THiNG ~~ "), | |
"spaceoddity" = normalize(" Space\t Oddity\n "), | |
"dontstopmenow" = normalize("Don\'t Stop Me Now"), | |
passed. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment