Created
April 12, 2010 19:33
-
-
Save gofullstack/363914 to your computer and use it in GitHub Desktop.
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
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