How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python?
>>> import random>>> print random.sample(xrange(100), 5)[61, 54, 91, 72, 85]
This should yield 5 unique values in the range 0 — 99
. The xrange
object generates values as requested so no memory is used for values that aren't sampled.
In Ruby:
a = (0..100).entries.sort_by {rand}.slice! 0, 5
Update: Here is a slightly different way: a = (0...100).entries.sort_by{rand}[0...5]
EDIT:
and In Ruby 1.9 you can do this:
Array(0..100).sample(5)
Hmm... How about (Python):
s = set()while len(s) <= N: s.update((random.random(),))