Last active
August 29, 2015 14:05
-
-
Save UberMouse/43abf82f7c4c7b4c4d06 to your computer and use it in GitHub Desktop.
Scala Palindromes
This file contains 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
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