Skip to content

Instantly share code, notes, and snippets.

@angch
Last active December 19, 2016 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angch/2d4408c3cc417104406963facf45ac7f to your computer and use it in GitHub Desktop.
Save angch/2d4408c3cc417104406963facf45ac7f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
)
var bitCounts = []uint8{}
func init() {
bitCounts = make([]uint8, 256, 256)
for n := 1; n <= 255; n++ {
count := uint8(0)
for k := uint8(n); k > 0; k >>= 1 {
if k&1 == 1 {
count++
}
}
bitCounts[n] = count
}
}
func prettyPrint(size uint8, num uint64) {
for ; size > 0; size-- {
if num&1 == 1 {
fmt.Print("B")
} else {
fmt.Print("A")
}
num >>= 1
}
fmt.Println("")
}
func listCombos(numA, numB uint8) {
size := uint8(numA + numB)
if size >= 64 {
fmt.Println("Sorry, too lazy to bignum this for now")
return
}
n := uint64(1 << size)
for i := uint64(0); i < n; i++ {
bits := uint8(0)
for j := i; j > 0; j >>= 8 {
bits = bits + bitCounts[j&0xff]
}
if bits == numB {
prettyPrint(size, i)
}
}
}
func countAB(ab string) (uint8, uint8) {
var a, b uint8
for i := 0; i < len(ab); i++ {
switch ab[i] {
case 'A':
a++
case 'B':
b++
}
}
return a, b
}
func main() {
input := ""
if len(os.Args) > 1 {
input = os.Args[1]
} else {
fmt.Println("Usage: combo2 AAB\nWhere AAB is the string of the combinations you're after")
return
}
a, b := countAB(input)
listCombos(a, b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment