Generate All Boolean Array Combinations
While writing Go tests for goxplorer, I wanted to test all boolean flags combinations without having to cascade for loops.
This first method came to mind:
package main
import (
"fmt"
)
func stob(bf []bool, s string) {
for i, b := range s {
if b == '0' {
bf[i] = false
} else {
bf[i] = true
}
}
}
func main() {
bf := []bool{false, false, false, false, false}
for i := 0; i < 32; i++ {
b := fmt.Sprintf("%b", i)
stob(bf, b)
fmt.Println(bf)
}
}
Because the fastest way of generating every possible combination of 5 bits is to count from 0 to 31, i.e. 2^5, i.e. 32. The second trick here is to use fmt.Sprintf("%b") to generate a string representing the binary value.
It works, but I found the idea of using strings too heavy for a “binary” task.
A friend came to me with a barbaric bits field solution I found way too smart / complicated :), so I thought about another option but also using bits field, and thought about the following: how to tell if a field is a 1? One of the many options is the or binary operator; indeed, if a field is 0 and is “or’ed” with a 1, its value will become 1, if the initial value is 1, it will not change. Remember or truth table?