Skip to content

Instantly share code, notes, and snippets.

@dgmltn
Last active December 23, 2015 09:53
Show Gist options
  • Save dgmltn/87a29d772f303401e5fe to your computer and use it in GitHub Desktop.
Save dgmltn/87a29d772f303401e5fe to your computer and use it in GitHub Desktop.
// Picks a random value from an arbitrary sequence
fun <T: Any> random(input: Observable<T>): Observable<T> {
var size = 1
return input
.filter { Math.floor(Math.random() * size++) == 0.0 }
.last()
}
// Test whether all items were chosen equally
fun test() {
val results = IntArray(5)
for (i in 1..10000) {
random(Observable.just(1, 2, 3, 4, 5)).subscribe { results[it-1]++ }
}
println(results.joinToString())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment