Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find a number of True statements in an Array of Bools in Swift

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  
        }        
    }
}
like image 848
bensams127 Avatar asked Oct 11 '16 19:10

bensams127


2 Answers

Methods for counting number of true entries in a 1D array

One 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

Applied to your example: use joined() to achieve a 1D array

The 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 }
like image 120
dfrib Avatar answered Dec 11 '22 07:12

dfrib


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, +)
like image 44
Sergey Kalinichenko Avatar answered Dec 11 '22 09:12

Sergey Kalinichenko