Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number within range with a seed

Tags:

php

I've been trying to wrap my head around solving this issue but I can't seem to find a simple solution to it.

I have a dynamic grid layout, articles are placed on the grid but have different width & height. This width & height of these different articles can change upon visiting the site but only when there is a new article added.

The issue is I have logic that uses mt_rand to generate random numbers within a range (to fit in the layout grid), is there a way I can pass in a seed (planning to use the newest article id) so that the random numbers are consistent until a new article is introduced? I wanted to use mt_srand but there doesn't seem to be an easy way to limit the random number within a range.

Thanks.

like image 678
David Nguyen Avatar asked Jun 01 '11 21:06

David Nguyen


People also ask

What is a seed in a random number?

What is a Random Seed? A random seed is a starting point in generating random numbers. A random seed specifies the start point when a computer generates a random number sequence. This can be any number, but it usually comes from seconds on a computer system's clock (Henkemans & Lee, 2001).

How do you randomly select a number from a range?

Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).

How random is random seed?

Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random() function generates numbers for some values. This value is also called seed value.

How do I randomize a number within a range in Excel?

If you want to use RAND to generate a random number but don't want the numbers to change every time the cell is calculated, you can enter =RAND() in the formula bar, and then press F9 to change the formula to a random number. The formula will calculate and leave you with just a value.


1 Answers

mt_srand() is used to set your seed and mt_rand() takes in a min and max if you want to set the range. Basically something like:

mt_srand($seed);
mt_rand($min, $max);

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

like image 66
Greg Field Avatar answered Sep 22 '22 04:09

Greg Field