Last active
August 29, 2015 14:21
-
-
Save dwo/767bf01e072d631da616 to your computer and use it in GitHub Desktop.
Choosing random array members deterministically based on contents of array and a name string
This file contains hidden or 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
require 'backports/1.9.1' if RUBY_VERSION < '1.9.1' | |
require 'backports/1.9.2' if RUBY_VERSION < '1.9.2' | |
require 'digest' | |
class Array | |
def deterministic_sample(n, name='') | |
seed = Digest::SHA1.hexdigest(self.sort.map(&:to_s).join << name).to_i(16) | |
prng = Random.new(seed) | |
self.sort.sample(n, :random => prng) | |
end | |
end | |
# output for ruby 1.8.7 | |
p ['a', 'b', 'c'].deterministic_sample(2) | |
# => ['c', 'a'] | |
p ['c', 'b', 'a'].deterministic_sample(2) | |
# => ['c', 'a'] | |
p | |
p ['a', 'b', 'c'].deterministic_sample(2, "foo") | |
# => ['b', 'c'] | |
p ['c', 'b', 'a'].deterministic_sample(2, "foo") | |
# => ['b', 'c'] | |
p | |
p ['a', 'b', 'c', 'd'].deterministic_sample(2) | |
# => ['c', 'd'] | |
p ['d', 'a', 'c', 'b'].deterministic_sample(2) | |
# => ['c', 'd'] | |
p | |
p ['a', 'b', 'c', 'd', 'e'].deterministic_sample(2) | |
# => ['d', 'b'] | |
p ['d', 'a', 'c', 'e', 'b'].deterministic_sample(2) | |
# => ['d', 'b'] |
This file contains hidden or 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
source 'https://rubygems.org' | |
gem 'backports' if RUBY_VERSION < '1.9.3' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment