我的问题与在数组数组中使用false
计算元素的有效方法有关。我现在如何迭代每个数组并计算元素是true
还是false
我看起来更有效率。
问题示例:
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
我的计数例子:
var count = 0
for x in 0..<board.count {
for y in 0..<board.count {
if board[x][y] == false {
count += 1
}
}
}
答案 0 :(得分:3)
我的3个解决方案:
使用reduce可以使用数组计算所有内容:
var countBoard1 = board.reduce(0, { $0 + $1.reduce(0, {$0 + (!$1 ? 1 : 0) })})
print(countBoard1)
我缩短最后一个缩小以过滤它然后我算一下:
var countBoard2 = board.reduce(0, { $0 + $1.filter{!$0}.count})
print(countBoard2)
因为每个数组元素都相等,所以我可以将数组展平为一个没有子数组的数组。然后我只过滤false
并计算这个结果:
var countBoard3 = board.flatMap{$0}.filter{!$0}.count
print(countBoard3)
计算结果:
[[false, true, true, false], [true, false, true, false], [true, true, false, false], [false, false, false, false]]
10
10
10