Ashwin Padhy
Ashwin Padhy

Reputation: 111

Checking multiple array elements and return true if all matched

I wanted to find if all emement of below array matched to each other:

val a = Array(1,1,1)
val b = Array(1,0,1)
val c = Array(0,1,1)

here output should be

Array(0,0,1) 

as all the value of a(2),b(2) and c(2) is 1 however for all cases it's 0. Is there any functional way of solving this in Scala?

Upvotes: 1

Views: 489

Answers (1)

Jeffrey Chung
Jeffrey Chung

Reputation: 19527

If the arrays are all the same size, then one approach is to transpose the arrays, then map-and-reduce the result with Java's bitwise AND operator &:

val a = Array(1, 1, 1)
val b = Array(1, 0, 1)
val c = Array(0, 1, 1)

val result = Array(a, b, c).transpose.map(_.reduce(_ & _)) // Array(0, 0, 1)

Upvotes: 10

Related Questions