Created
October 17, 2014 20:37
-
-
Save whyrusleeping/bd3c6c29d24521f2d168 to your computer and use it in GitHub Desktop.
generate all subsequences of a string
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" | |
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