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
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 ;)

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

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);

}

}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.