Skip to content

Instantly share code, notes, and snippets.

@bartimaeus
Created December 7, 2010 20:29
Show Gist options
  • Save bartimaeus/732352 to your computer and use it in GitHub Desktop.
Save bartimaeus/732352 to your computer and use it in GitHub Desktop.
Trying to solve a challenge given to me yesterday to write a script that tests for palindromes on strings with unknown length and no special characters (alphanumeric only)
#!/bin/ruby
# I want to make this a class, but until I get all the
# bugs worked out it will just be a script :-)
#class Palindrome
def isPalindrome(string)
palindrome = true
reverse = string.reverse
limit = string.length % 2 == 0 ? string.length / 2 : string.length / 2 + 1
for i in 0...limit
palindrome = string[i] == reverse[i]
return false if !palindrome # don't bother to continue if we hit a failed case
end
return palindrome
end
# Discover palindromes from a string
def discover(string)
@palindromes = []
# Do a palindrome check on each index, b/c there may be
# more than one paleindrome overlapping one another
for i in 0...string.length
# Now find palindromes from this index forward (smallest possible case is three characters)
for j in 3...string[i...string.length].length + 1
# Create a substring to test if it's a palindrome
palindrome = string[i...i+j]
# Add the palindrome to the instance variable if a palindrome is found
@palindromes.push(palindrome) if isPalindrome(palindrome)
end
end
# Print palidromes found
puts @palindromes
end
#end
discover("ababcba") # There should be 4 palindromes found from this string ("aba", "bab", "abcba", "bcb")
@bartimaeus
Copy link
Author

Putting this on hold to get back to work :-) It's the end of my lunch break.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment