gpt4 book ai didi

具有相同相邻值的Scala列表

转载 作者:行者123 更新时间:2023-12-04 00:08:25 25 4
gpt4 key购买 nike

我有这个 list :

List("Black","Black","Green","White")

如何检查列表是否有两个相同的相邻值?像这样:
List("Black","Black","Green","White") true

List("Black","Yellow","Green","White") false

List("Black","Yellow","Black","Yellow") false

最佳答案

除了Valy Dia的解决方案,你还可以这样写:

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

关于具有相同相邻值的Scala列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56359114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com