Skip to content

Instantly share code, notes, and snippets.

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 christianchristensen/364633 to your computer and use it in GitHub Desktop.
Save christianchristensen/364633 to your computer and use it in GitHub Desktop.
module Enumerable
# Iterate over this array randomly.
# From: http://stackoverflow.com/questions/2459913/how-can-i-randomly-iterate-through-a-large-range
# And: http://refactormycode.com/codes/40-is_prime
def randomized
return to_enum(:randomized) unless block_given?
def is_prime?(num)
i = 3
return false if num % 2 == 0 && num != 2
ss = Math.sqrt(num).floor
return false if ss**2 == num
while i <= ss
return false if num % i == 0
i += 2
end
true
end
def next_prime(i)
if i % 2 == 0
i += 1
end
until is_prime?(i)
i += 2
end
i
end
n = self.size
q = next_prime(( 2 * n / (1 + Math.sqrt(5)) ).to_i)
index = start = Kernel.rand(n)
def next_index(i, q, n)
(i + q) % n
end
begin
yield self[index]
index = next_index(index, q, n)
end until index == start
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment