0

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

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
  }
}
4
  • 3
    Arrays in scala zero based. Commented Oct 2, 2020 at 9:58
  • 1
    Somewhat off-topic, but if (booleanCheck) true else false can just be written as booleanCheck since that expression returns a Boolean anyway. Commented Oct 2, 2020 at 10:35
  • You are not returning anything. Commented Oct 2, 2020 at 13:01
  • even If when I store the result of if expression it shows the unit error Commented Oct 2, 2020 at 14:08

1 Answer 1

3

You can use sliding that

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))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.