I am a new developer and cannot seem to figure out how to find the number of True statements in an Array of Booleans. I know how to find by index but not by value. Any assistance would be appreciated.
let arrayElement = [Bool](repeating: false, count: 10)
var before: [[Bool]] = [[Bool]](repeating: arrayElement, count:10)
for i in 0 ..< 10 {
for j in 0 ..< 10 {
if arc4random_uniform(3) == 1 {
before[i][j] = true
}
}
}
true
entries in a 1D arrayOne method would be to filter your array of Bool
elements (for true
) and simply count the number of remaining elements in the filtered array
let arr = [false, true, true, false, true]
let numberOfTrue = arr.filter{$0}.count
print(numberOfTrue) // 3
Another approach is to reduce
(unfold) the array and increment a counter for each element that equals true
let arr = [false, true, true, false, true]
let numberOfTrue = arr.reduce(0) { $0 + ($1 ? 1 : 0) }
print(numberOfTrue) // 3
Or, a traditional for
loop (with conditional in loop signature) approach, comparable top the reduce
method:
let arr = [false, true, true, false, true]
var trueCounter = 0
for bElem in arr where bElem { trueCounter += 1 }
print(trueCounter) // 3
joined()
to achieve a 1D arrayThe methods above can easily be applied to an array of arrays (of Bool
elements: type [[Bool]]
) by simply applying .joined()
on the [[Bool]]
array to sequentially construct a [Bool]
array.
/* 'before' is of type [[Bool]], constructed as described
in the question */
let numberOfTrueAlt1 = before.joined().filter{$0}.count
let numberOfTrueAlt2 = before.joined().reduce(0) { $0 + ($1 ? 1 : 0) }
var numberOfTrueAlt3 = 0
for bElem in before.joined() where bElem { numberOfTrueAlt3 += 1 }
Since you are dealing with an array of arrays, the computation will have two steps as well. First, use map
to convert each inner array to its truth count, and then aggregate with reduce
to obtain the final result:
let countTrue = before.map {$0.filter{$0}.count}.reduce(0, +)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With