HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Find a palindrome using Ruby

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
palindromerubyusingfind

Problem

I am preparing for an upcoming exam and have the following practice question..


Write a method to determine if a word is a palindrome, without using
the reverse method.

Most of you probably know what a palindrome is, but for those that don't.. a palindrome is a word which reads the same backward or forward.

Anyway, here's my answer to the question. I've written my own reverse method as directed.

How would you refactor this?

def reverse(word_arr)
  reverse = []
  index = word_arr.length
  until index == 0 do
    reverse << word_arr[index - 1]
    index -= 1
  end
  reverse
end

def is_palindrome?(word)
  word_arr = word.downcase.gsub(/ /,'').split('')
  true if word_arr == reverse(word_arr)
end

p is_palindrome?('Anna')
p is_palindrome?('Joe')
p is_palindrome?('Go dog')

Solution

What if you changed the algorithm to do the following steps?

  • Remove all Spaces



  • If String Length is Odd, delete middle character



  • Split string in half



  • Reverse one of the halves



  • Compare the two halves



Rationale: In your case, you reverse the entire string, even when it's very large, when you really only need to reverse the first half of the string.

Context

StackExchange Code Review Q#121004, answer score: 2

Revisions (0)

No revisions yet.