Skip to content

Commit

Permalink
Merge 9c0f05d into d129474
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Sep 5, 2018
2 parents d129474 + 9c0f05d commit f8abc86
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
25 changes: 25 additions & 0 deletions day15/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package day15

import (
"math/rand"
"time"
)

var randomizer *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))

// UniformlyRandom reads from a stream of anything and
// returns an element with uniform probabilty.
// O(N) time and O(1) space
func UniformlyRandom(stream <-chan interface{}) interface{} {
var result interface{}
var count int
for element := range stream {
if count == 0 {
result = element
} else if randomizer.Intn(count) == 0 {
result = element
}
count++
}
return result
}
36 changes: 36 additions & 0 deletions day15/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package day15

import (
"math/rand"
"testing"
)

func TestUniformlyRandom(t *testing.T) {
t.Parallel()
randomizer = rand.New(rand.NewSource(99)) // use a fixed seed for testing.
expected := 58 // because of the constant random seed
input := make(chan interface{})
go func() {
for i := 0; i < 100; i++ {
input <- i
}
close(input)
}()
if result := UniformlyRandom(input); result != 58 {
t.Errorf("Expected %v but got %v", expected, result)
}
}

func BenchmarkUniformlyRandom(b *testing.B) {
randomizer = rand.New(rand.NewSource(99)) // use a fixed seed for testing.
for i := 0; i < b.N; i++ {
input := make(chan interface{})
go func() {
for i := 0; i < 100; i++ {
input <- i
}
close(input)
}()
UniformlyRandom(input)
}
}

0 comments on commit f8abc86

Please sign in to comment.