I have this list:
List("Black","Black","Green","White")
How can I check if a list has two adjacent values which are the same? Like so:
List("Black","Black","Green","White") true
List("Black","Yellow","Green","White") false
List("Black","Yellow","Black","Yellow") false
In addition to Valy Dia's solution, you can also write:
list.sliding(2).exists(_.distinct.size == 1)
scala> def check[A](l: Seq[A]): Boolean = l.sliding(2).exists(_.distinct.size == 1)
check: [A](l: Seq[A])Boolean
scala> check("A" :: "B" :: Nil)
res0: Boolean = false
scala> check("A" :: "B" :: "B" ::Nil)
res1: Boolean = true
scala> check("A" :: "B" :: "C":: "B" ::Nil)
res2: Boolean = false
You can try:
def check[A](l: List[A]): Boolean =
l.zip(l.tail).exists{ case (x,y) => x == y }
check(List("Black","Black","Green","White"))
//res5: Boolean = true
check(List("Black","Yellow","Green","White"))
//res6: Boolean = false
check(List("Black","Yellow","Black","Yellow"))
//res7: Boolean = false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With