Skip to content

Instantly share code, notes, and snippets.

@xbeta
Created March 7, 2015 07:24
Show Gist options
  • Save xbeta/233c80046610b6b66674 to your computer and use it in GitHub Desktop.
Save xbeta/233c80046610b6b66674 to your computer and use it in GitHub Desktop.
Reservoir Sampling - algorithm from wiki (http://en.wikipedia.org/wiki/Reservoir_sampling)
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