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

前端 未结 2 509
忘掉有多难
忘掉有多难 2020-12-11 03:03

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 assis

相关标签:
2条回答
  • 2020-12-11 03:19

    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 }
    
    0 讨论(0)
  • 2020-12-11 03:25

    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, +)
    
    0 讨论(0)
提交回复
热议问题