Last active
August 20, 2025 04:13
-
-
Save gammazero/2b8e82cffa397c7fbc49a9fd9c4f4dde to your computer and use it in GitHub Desktop.
Generate bit strings
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
| package main | |
| import "fmt" | |
| // BitStrings generates all combinations of binary values, as strings, having | |
| // the specified number of bits. | |
| func BitStrings(n int) []string { | |
| if n <= 0 { | |
| return nil | |
| } | |
| rdCap := 1 << (n - 1) | |
| wrCap := 1 << n | |
| if n&1 == 1 { | |
| rdCap, wrCap = wrCap, rdCap | |
| } | |
| rd := make([]string, 0, rdCap) | |
| wr := make([]string, 1, wrCap) | |
| for range n { | |
| rd, wr = wr, rd[:0] | |
| for _, s := range rd { | |
| wr = append(wr, s+"0", s+"1") | |
| } | |
| } | |
| return wr | |
| } | |
| func main() { | |
| fmt.Println("BitStrings(1):", BitStrings(1)) | |
| fmt.Println("BitStrings(2):", BitStrings(2)) | |
| fmt.Println("BitStrings(3):", BitStrings(3)) | |
| } | |
| // https://go.dev/play/p/dyWHTTj8wNe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment