Skip to content

Instantly share code, notes, and snippets.

@whyrusleeping
Created October 17, 2014 20:37
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 whyrusleeping/bd3c6c29d24521f2d168 to your computer and use it in GitHub Desktop.
Save whyrusleeping/bd3c6c29d24521f2d168 to your computer and use it in GitHub Desktop.
generate all subsequences of a string
package main
import "fmt"
type seqGen struct {
baseStr string
curI int
ch chan string
}
func NewSeqGen(s string) chan string {
sg := new(seqGen)
sg.baseStr = s
sg.ch = make(chan string)
sg.curI = int(1<<uint(len(s))) - 1
go sg.Start()
return sg.ch
}
func (sg *seqGen) Start() {
for sg.curI >= 0 {
sg.ch <- maskString(sg.baseStr, sg.curI)
sg.curI--
}
close(sg.ch)
}
func maskString(s string, mask int) string {
var out string
for i := uint(0); i < uint(len(s)); i++ {
if mask&(1<<i) != 0 {
out += s[i : i+1]
}
}
return out
}
func main() {
for s := range NewSeqGen("abc") {
fmt.Printf("'%s'\n", s)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment