Use rand(range)
From Ruby Random Numbers:
If you needed a random integer to simulate a roll of a six-sided die, you'd use: 1 + rand(6)
. A roll in craps could be simulated with 2 + rand(6) + rand(6)
.
Finally, if you just need a random float, just call rand
with no arguments.
As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random
class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).
For instance, in this game where you need to guess 10 numbers, you can initialize them with:
10.times.map{ 20 + Random.rand(11) }
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]
Note:
This is why the equivalent of Random.new.rand(20..30)
would be 20 + Random.rand(11)
, since Random.rand(int)
returns “a random integer greater than or equal to zero and less than the argument.” 20..30
includes 30, I need to come up with a random number between 0 and 11, excluding 11.
Every time you do new Random()
it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.
//Function to get a random number
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
lock(syncLock) { // synchronize
return random.Next(min, max);
}
}
Edit (see comments): why do we need a lock
here?
Basically, Next
is going to change the internal state of the Random
instance. If we do that at the same time from multiple threads, you could argue "we've just made the outcome even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random
does not make any guarantees of thread-safety. Thus there are two valid approaches:
- Synchronize so that we don't access it at the same time from different threads
- Use different
Random
instances per thread
Either can be fine; but mutexing a single instance from multiple callers at the same time is just asking for trouble.
The lock
achieves the first (and simpler) of these approaches; however, another approach might be:
private static readonly ThreadLocal<Random> appRandom
= new ThreadLocal<Random>(() => new Random());
this is then per-thread, so you don't need to synchronize.
Best Answer
Take a look @
http://dx3webs.com/front/2010/10/how-to-create-a-random-featured-product-list-on-home-page-in-magento/Also try changing
to
or
see /app/code/core/Mage/Catalog/Block/Product/List/Random.php
You could also try adding this to your cms page