-
Notifications
You must be signed in to change notification settings - Fork 68
/
PalinDome.rb
43 lines (34 loc) · 1.35 KB
/
PalinDome.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
=begin
A palindrome is a word, phrase, number, or other sequence of symbols or
elements, whose meaning may be interpreted the same way in either forward or
reverse direction. Famous examples include "Amore, Roma", "A man, a plan, a
canal: Panama" and "No 'x' in 'Nixon'". - wikipedia
Our goal is to determine whether or not a given string is a valid palindrome
or not.
Like the above examples, here are a few test cases which are also populated:
"Amore, Roma" => valid
"A man, a plan, a canal: Panama" => valid
"No 'x' in 'Nixon'" => valid
"Abba Zabba, you're my only friend" => invalid
You can see that they are case insensitive and disregards non alphanumeric
characters. In addition to a few predefined tests, your function will also be
tested against a random string generator 50 times which are guaranteed to
produce valid palindromes.
Notes:
reverse/reverse! have been disabled for String/Array and reverse() for JS.
reverse cannot get used in Haskell either
the empty string "" can be read forward or backward the same, it's a palindrome
in our case.
=end
# My Solution
def palindrome(string)
forward = string.gsub(/\W/,"").downcase
back = ""
(forward.length-1).downto(0) {|x| back += forward[x]}
forward == back
end
# Better Solution
def palindrome(string)
string = string.downcase.tr('^a-z','')
string == string.chars.reduce('') { |w,c| c + w }
end