-
-
Save joshnuss/008dfd539bcd4e35ab8c to your computer and use it in GitHub Desktop.
This file contains 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
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