Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala list with same adjacent values

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
like image 849
jakstack Avatar asked May 29 '19 11:05

jakstack


2 Answers

In addition to Valy Dia's solution, you can also write:

list.sliding(2).exists(_.distinct.size == 1)

REPL Session

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
like image 88
ziggystar Avatar answered Oct 01 '22 02:10

ziggystar


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
like image 35
Valy Dia Avatar answered Oct 01 '22 02:10

Valy Dia