2

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
        }
    }
}
3
  • 1
    Update your question with your attempt to count the false values. Commented Jan 28, 2017 at 23:01
  • @rmaddy i add my attempt Commented Jan 28, 2017 at 23:04
  • board.forEach { $0.forEach { count += !$0 ? 1 : 0 } } Commented Jan 28, 2017 at 23:54

1 Answer 1

3

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