Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Forked from alco/reservoir.exs
Last active August 29, 2015 14:04
Show Gist options
  • Save joshnuss/008dfd539bcd4e35ab8c to your computer and use it in GitHub Desktop.
Save joshnuss/008dfd539bcd4e35ab8c to your computer and use it in GitHub Desktop.
defmodule Enum2 do
import Enum
def sample(collection),
do: hd(sample(collection, 1))
# http://en.wikipedia.org/wiki/Reservoir_sampling
def sample(collection, count) do
results = take(collection, count)
collection
|> Stream.drop(count)
|> Stream.with_index
|> reduce(results, fn {value, index}, acc ->
case :random.uniform(index+1)-1 do
random when random < count -> List.replace_at(acc, random, value)
_ -> acc
end
end)
end
end
arr = 0..1000000 |> Enum.to_list
IO.puts "slow"
IO.inspect(arr |> Enum.shuffle |> Enum.take(100))
IO.puts "fast"
IO.inspect Enum2.sample(arr, 100)
IO.puts "fast"
IO.inspect Enum2.sample(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment