Last active
November 8, 2023 16:29
-
-
Save rodmoioliveira/ac0cf7e41aca59c83cce4b4f8f1efe76 to your computer and use it in GitHub Desktop.
Bit sets in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://rm-o.dev/blog/basic-set-operations-in-golang/ | |
| package main | |
| import ( | |
| "fmt" | |
| "math/bits" | |
| ) | |
| const ( | |
| sat uint8 = 1 << iota // (0b0000001) -> {sat} | |
| fri // (0b0000010) -> {fri} | |
| thu // (0b0000100) -> {thu} | |
| wed // (0b0001000) -> {wed} | |
| tue // (0b0010000) -> {tue} | |
| mon // (0b0100000) -> {mon} | |
| sun // (0b1000000) -> {sun} | |
| ) | |
| func main() { | |
| bob := sun | thu | fri | sat | |
| alice := tue | thu | sat | |
| daysWorkingTogether := alice & bob | |
| cardinality := bits.OnesCount8(daysWorkingTogether) | |
| fmt.Printf("Sequence (%07b) represents the set {sun,thu,fri,sat}, which are the working days of Bob.\n", bob) | |
| fmt.Printf("Sequence (%07b) represents the set {tue,thu,sat}, which are the working days of Alice.\n", alice) | |
| fmt.Printf( | |
| "Sequence (%07b) represents the set {thu,sat}, which are the days that Alice and Bod work together: %02x\n", | |
| daysWorkingTogether, | |
| cardinality, | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment