Simple palindrome example using scala
1) reading the input in a variable
scala> val s="sasas"
s: String = sasas
2)spliting and comparing the string first and last as per palindrome rule.
scala> (for (x <- 0 to s.length/2) yield (s(x) == s(s.length - x - 1)))
res2: scala.collection.immutable.IndexedSeq[Boolean] = Vector(true, true, true)
3)see whether it is true or false using Boolean member.
scala> .reduceLeft((a,b)=> a && b)
res3: Boolean = true
Use the same as a function
def isPalindrome(s: String) = {
(for (x <- 0 to s.length/2) yield (s(x) == s(s.length - x - 1)))
.reduceLeft((a,b)=> a && b)
}
No comments:
Post a Comment