Created
March 7, 2015 07:24
-
-
Save xbeta/233c80046610b6b66674 to your computer and use it in GitHub Desktop.
Reservoir Sampling - algorithm from wiki (http://en.wikipedia.org/wiki/Reservoir_sampling)
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 ( | |
"time" | |
"math/rand" | |
"fmt" | |
) | |
func randInt(min int, max int) int { | |
return min + rand.Intn(max-min) | |
} | |
func main() { | |
const SIZE = 10 | |
rand.Seed(time.Now().UTC().UnixNano()) | |
var sample []int // the reservoir | |
largeSet := make([]int, 1000000) // holds the random large set | |
for i := 0; i < 1000000; i++ { largeSet[i] = rand.Intn(100) } | |
for index, value := range largeSet { | |
// Generate the reservoir | |
if (index < SIZE ){ | |
sample = append(sample, value) | |
}else{ | |
// Randomly replace elements in the reservoir | |
// with a decreasing probability. | |
// Choose an integer between 0 and index (inclusive) | |
r := randInt(0,index) | |
if (r < SIZE) { | |
sample[r] = value | |
} | |
} | |
} | |
fmt.Println(sample) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment