Edhelvar Edhelvar - 1 year ago 53
Scala Question

Scala - Count number of adjacent repeated chars in String

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

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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download