简体   繁体   English

成对比较数组 Scala

[英]Pairwise comparison array Scala

I 'm trying to compare if two consecutive elements of an array are equal.我试图比较数组的两个连续元素是否相等。

I have tried using for but as it returns a boolean but it does not seem to work what am I missing我试过使用 for 但因为它返回一个布尔值但它似乎不起作用我错过了什么

val array1 = Array(1, 4, 2, 3)

def equalElements(array : Array[Int]) : Boolean = {
  
  for (i <- 1 to  (array.size )) {
    if (array(i) == array(i + 1)) true else false
  }
}

You can use sliding that你可以使用sliding

Groups elements in fixed size blocks by passing a "sliding window" over them (as opposed to partitioning them, as is done in grouped.)通过在固定大小的块上传递一个“滑动窗口”来对元素进行分组(而不是像分组那样对它们进行分区。)

val array1 = Array(1, 1, 2, 2)
val equalElements = array1
  .sliding(size = 2, step = 1) //step = 1 is a default value.
  .exists(window => window.length == 2 && window(0) == window(1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM