Jump to content

Question about Random Numbers?


Solarpitch

Recommended Posts

Hi,

 

I'm trying to create a Random number function that will select a number between 1 and 7. This is fine. But what I need to do is put in a constraint where the higher the number, the less chance there is of it being selected in the function:

 

For example:

 

1 - almost always selected from the function

2 - selected frequently

...

6 - very rare

7 - once every blue moon!

 

What way can I approach this in order to manipulate a random function in controlling what it selects?

Link to comment
https://forums.phpfreaks.com/topic/174813-question-about-random-numbers/
Share on other sites

Could you check that if a 7 is found, then it generates another random number and so on.

 

if 1 is found, it is found

 

if 2 is found, regen

 

if 3 is found, regen if again?>regen

 

that would mean a blue moon would occur when a randomly generated number is randomly generated 7 times in a row ;)

Depends how you are generating this number.

 

you could randomly pick from an array

 

array(1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,4,4,4,4,5,5,5,6,6,7);

 

means the chance of a 7 are slim compared to 1.maybe even "randomly" order the array itself first?

I suppose you could do something like this:

 

<?php
function getRand($low, $high)
{
$main = Array();
for($i = $low;$i <= $high;$i++)
	$main = array_merge($main, array_fill(0, $high-$i+1, $i));
return $main[array_rand($main)];
}

echo getRand(1, 7);

Umm.. interesting. Thanks for that guys. I'm gonna have a look at it here now and see what way is best. Here's how I'm generating the number anyway:

 


			 $min = 1;
			 $max = 7;

			srand ((double) microtime( )*1000000);
			$random = rand($min,$max);

 

Ok.. this seems to be working fine. Say 4 is chosen randomly from the array, what I then want to do is query my members table, get the min and max id and return 4 random members from the members table.

 

So if I have 1000 members, it will get 4 member id's from 1 - 1000. Again, this is fine.. but, each of the 4 random id's returned must be unique.. the same id cant be chosen twice. Here's what I have.

 

<?php

... above function we just discussed returns 4...

$arr = array();
for ($i = 0; $i < 4; $i++) {


$get_min_max = $this->user_model->get_min_max();
foreach($get_min_max as $row){

$min = $row->min_id; // 1
$max = $row->max_id; // 1000

srand ((double) microtime( )*1000000);
$random_profile = rand($min,$max);


}

if(in_array($random_profile, $arr)){
// member id already in the array.. we need to get another one
}else{
// if its not in the array, add it
$arr[] = array($i => $random_profile);

}

}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.