Last active
August 29, 2015 14:19
-
-
Save benjic/b339995e1ad0a9e191ca to your computer and use it in GitHub Desktop.
Provides a concurrent safe iterator for generating bitstring combinations of given length.
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 hamming | |
// An asynchronous permutation Iterator for bitstrings | |
// So you want all the permuations of 3 bits choose 2 at a time? Well just | |
// create this async iterator which produces these bitstrings as there integer | |
// equivlent. | |
// | |
// bspIterator(3,2) | |
// 011 = 3 | |
// 101 = 5 | |
func bspIterator(n, k int) chan int64 { | |
// Create buffer to pass integer of bitstring | |
ch := make(chan int64, 0) | |
// Recursive defintion | |
switch { | |
case k == 1: | |
// This is the base case when asking for n choose one bit | |
go func() { | |
for i := 0; i < n; i++ { | |
ch <- 1 << uint(i) | |
} | |
// Signal the consumer that the end is nigh | |
close(ch) | |
}() | |
case k > 1: | |
// The is the recursive step in which a logical or of every bit with | |
// every permutation of n choose k-1 bits | |
go func() { | |
for i := range bspIterator(n, k-1) { | |
for j := 0; j < n; j++ { | |
// We test for equivlent permutations and throw it out | |
if 1<<uint(j) != uint(i) { | |
// A logical or with a lesser n choose k call will produce | |
// all n choose k permutations | |
ch <- 1<<uint(j) | i | |
} | |
} | |
} | |
// Signal the consumer that the end is nigh | |
close(ch) | |
}() | |
} | |
return ch | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment