pseudo-randomize an array in a consistent order

M

Max Williams

Here's my final version in case anyone's interested:

class Array

def randomize!(seed=nil)
srand(seed) if seed
i = length - 1
while (i > 0)
#have to specify Kernel::rand to avoid method name clash
j = Kernel::rand(i)
# Swap self and self[j]
tmp = self
self = self[j]
self[j] = tmp
i -= 1
end
#reset srand
srand if seed
self
end

def randomize(seed=nil)
self.dup.randomize!(seed)
end

end

I encountered a puzzling gotcha with rand - it turns out that Rails
monkey-patches Array with 'rand' (no arguments) which pulls out a random
element. So, calling

j = rand(i)

was giving me a 'too many arguments' error, as it thought i was wanting
Array::rand. So, i just specify that i want Kernel::rand and it's fine.

thanks again
max
 
D

David A. Black

Here's my final version in case anyone's interested:

class Array

def randomize!(seed=nil)
srand(seed) if seed
i = length - 1
while (i > 0)
#have to specify Kernel::rand to avoid method name clash
j = Kernel::rand(i)
# Swap self and self[j]
tmp = self
self = self[j]
self[j] = tmp
i -= 1
end
#reset srand
srand if seed
self
end

def randomize(seed=nil)
self.dup.randomize!(seed)
end

end


I don't think it randomizes very well.
1000.times { puts "yes!" if [1,2].randomize == [1,2] }
=> 1000
I encountered a puzzling gotcha with rand - it turns out that Rails
monkey-patches Array with 'rand' (no arguments) which pulls out a random
element.

I'd describe that as a gotcha with Rails :)


David
 
M

Max Williams

David said:
I don't think it randomizes very well.
1000.times { puts "yes!" if [1,2].randomize == [1,2] }
=> 1000
David

Well spotted - this is the offending line:

j = Kernel::rand(i)

It means (effectively) that a number can never stay in the same place,
which breaks the randomness a bit (and totally breaks it for two-element
arrays). Changing it to this

j = Kernel::rand(i+1)

seems to fix it.

thanks!
max
 
M

Max Williams

It means (effectively) that a number can never stay in the same place,

Err by 'number' i mean 'element' of course (elements just happen to be
numbers in the example).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top