1

I have this function that counts the number of adjacent repeated chars inside a String.

def adjacentCount( s: String ) : Int = {
    var cont = 0
    for (a <- s.sliding(2)) {
        if (a(0) == a(1)) cont = cont + 1
    }
        cont
    }
}

But I'm supposed to create a function that does exactly the same, but using only immutable variables or loop instructions, in a "purely" functional way.

1 Answer 1

5

You can just use the count method on the Iterator:

val s = "aabcddd"

s.sliding(2).count(p => p(0) == p(1))
// res1: Int = 3
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.