Search code examples
gosumbooleanboolean-operations

How to get "sum" of true bools


In this scenario I have 3x boolean vars (already set to either true or false)

The goal here is to identify if more than one of the set of bool vars are set to true

Right now I have the following written, which does work:

    boolval := 0
    if *firstbool {
        boolval++
    }
    if *secondbool {
        boolval++
    }
    if *thirdbool {
        boolval++
    }
    if boolval > 1 {
        // More than 1 of the bool vars are true
    }

I always flag my logic if I am writing successive if{} statements, so I figured I would ask you geniuses how you would accomplish this.


Solution

  • identify if more than one of the set of bool vars are set to true


    For example, write a set function:

    package main
    
    import "fmt"
    
    func nTrue(b ...bool) int {
        n := 0
        for _, v := range b {
            if v {
                n++
            }
        }
        return n
    }
    
    func main() {
        v1, v2, v3 := true, false, true
    
        fmt.Println(nTrue(v1, v2, v3))
    
        if nTrue(v1, v2, v3) > 1 {
            // . .   .
        }
        // Or
        if n := nTrue(v1, v2, v3); n > 1 {
            // . .   .
        }
        // Or
        n := nTrue(v1, v2, v3)
        if n > 1 {
            // . .   .
        }
    }
    

    Playground: https://play.golang.org/p/g3WCN6BgGly

    Output:

    2
    

    For example, range over the set,

    package main
    
    import "fmt"
    
    func main() {
        v1, v2, v3 := true, false, true
    
        boolval := 0
        for _, v := range []bool{v1, v2, v3} {
            if v {
                boolval++
            }
        }
        if boolval > 1 {
            // . .   .
        }
    
        fmt.Println(boolval > 1, boolval)
    }
    

    Playground: https://play.golang.org/p/R6UGb8YYEFw

    Output:

    true 2