Skip to content

Instantly share code, notes, and snippets.

@UberMouse
Last active August 29, 2015 14:05
Show Gist options
  • Save UberMouse/43abf82f7c4c7b4c4d06 to your computer and use it in GitHub Desktop.
Save UberMouse/43abf82f7c4c7b4c4d06 to your computer and use it in GitHub Desktop.
Scala Palindromes
def isPalindromeReversing(str: String): Boolean = str.reverse == str
def isPalindrome(str: String) = {
val half = str.length / 2
val firstHalf = str.take(half)
val secondHalf = str.drop({
if(str.length % 2 != 0)
half + 1
else
half
})
firstHalf.foldLeft(new scala.collection.immutable.Stack[Char]) {
case(stack, pushChar) => stack.push(pushChar)
}.zip(secondHalf).forall{case(l, r) => l == r}
}
val results = List(
("1221", true),
("14761255216741", true),
("173", false)
)
List(isPalindromeReversing _, isPalindrome _).forall(f => {
results.map{case(test, answer) => f(test) == answer}.forall(identity)
}) == true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment