Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

How to count `false` elements of the Array of Arrays

My issue is connected with efficient way to count elements with false in the array of arrays. I now how iterate each array and count if element is true or false i am looking more efficient way.

Example of the problem:

let n = 4
var board = Array(repeating:Array(repeating:true, count:n), count:n)

let qPos  = [4,4]

board[qPos[0] - 1][qPos[1] - 1] = false


for x in 0..<n{
    for y in 0..<n {
        if (x == qPos[0] - 1) {
            board[x][y] = false
        }

        if (y == qPos[1] - 1) {
            board[x][y] = false
        }

        if (y == x) {
             board[x][y] = false
        }
    }
}
//How to calculate all negative elements of the board ? In this code output should be 10

My example of count:

var count = 0
for x in 0..<board.count {
    for y in 0..<board.count {
        if board[x][y] == false {
            count += 1
        }
    }
}

Upvotes: 2

Views: 113

Answers (1)

muescha
muescha

Reputation: 1539

my 3 solutions:

with reduce you can calculate everything with your arrays:

var countBoard1 = board.reduce(0, { $0 + $1.reduce(0, {$0 + (!$1 ? 1 : 0) })})
print(countBoard1)

i short the last reduce to filter it and then i count it:

var countBoard2 = board.reduce(0, { $0 + $1.filter{!$0}.count})
print(countBoard2)

because every array element counts equal i can flatten the array in to one array without subarrays. then i filter only the false and count this result:

var countBoard3 = board.flatMap{$0}.filter{!$0}.count
print(countBoard3)

count result:

[[false, true, true, false], [true, false, true, false], [true, true, false, false], [false, false, false, false]]
10
10
10

Upvotes: 3

Related Questions