Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/8907567 to your computer and use it in GitHub Desktop.
Save JoshCheek/8907567 to your computer and use it in GitHub Desktop.
Keep getting the same value for next_seed as I get for seed.
class RandomCollectionQueue
def initialize(seed, collection)
random = ::Random.new seed
self.collection = collection
self.seed = seed
self.next_seed = random.rand
self.block_index = random.rand collection.size
p [seed, next_seed]
end
def dequeue
@dequeued ||= [
self.class.new(next_seed, collection),
collection[block_index]
]
end
private
attr_accessor :seed, :next_seed, :block_index, :collection
end
q = RandomCollectionQueue.new rand, [*1..10]
q, n = q.dequeue # => [#<RandomCollectionQueue:0x007fafe8b49a70 @collection=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], @seed=0.5488135039273248, @next_seed=0.5488135039273248, @block_index=5>, 6]
q, n = q.dequeue # => [#<RandomCollectionQueue:0x007fafe8b53980 @collection=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], @seed=0.5488135039273248, @next_seed=0.5488135039273248, @block_index=5>, 6]
q, n = q.dequeue # => [#<RandomCollectionQueue:0x007fafe8b52238 @collection=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], @seed=0.5488135039273248, @next_seed=0.5488135039273248, @block_index=5>, 6]
# >> [0.5799812254037409, 0.5488135039273248]
# >> [0.5488135039273248, 0.5488135039273248]
# >> [0.5488135039273248, 0.5488135039273248]
# >> [0.5488135039273248, 0.5488135039273248]
@JoshCheek
Copy link
Author

Figured it out. It's a fucking type error. Kernel.rand returns a float between 0 and 1. Random#initialize must call Float#to_i on it, meaning it seeds with 0 every time.

Random.new(Random.new(Random.new(Kernel.rand  # => 0.9588543389818969
                                ).rand        # => 0.5488135039273248
                     ).rand                   # => 0.5488135039273248
          ).rand                              # => 0.5488135039273248

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment