Justin John
Justin John

Reputation: 9616

Make an random value from array where most selected value will one

How to get random value from array set an value in array that will be one to selected more than other?

array('00','01','02');

I want to select an random value from this array with most selected value be '00', i.e the '00' value will be selected 80% and other two values will be 20%.

Here array can have many values, its only an example with three values

Upvotes: 0

Views: 377

Answers (4)

Rajat Singhal
Rajat Singhal

Reputation: 11264

$main_array=array('00','01','02');

$priority=array(0,0,0,0,0,0,0,0,1,2);

$rand_index=array_rand($priority);//select a random index from priority array.. $priority[$rand_index] will give you index 0 or 1 or 2 with your priority set..

echo $main_array[$priority[$rand_index]];

I think the code is self explanatory...

Array will have many elements case will come when lets say the requirement will come like 3% probability of "00" 28% prob. of "01" rest to other elements...In that case use array_fill function to fill elements in masses...and array_merge them

Like for the same case I've taken answer will be

$main_array=array('00','01','02');
$priority1=array_fill(0,69,2);
$priority2=array_fill(0,28,1);
$priority3=array_fill(0,3,0);    
$priority=array_merge($priority1,$priority2,$priority3);

$rand_index=array_rand($priority);

echo $main_array[$priority[$rand_index]];

Upvotes: 2

Gray Gaffer
Gray Gaffer

Reputation: 111

Use a parallel array with the probability distribution, e.g.:

array('80', '10', '10');

Use standard random number function to generate a number between 0 and 99, then look it up in this array. The index you find it at is then used as the index to the values array.

Upvotes: 0

user557846
user557846

Reputation:

one of many options

$a = array_fill(0, 8, '0');
$a['9']='1';
$a['10']='2';

echo $a[array_rand($a,1)];

Upvotes: 0

Jake Stoeffler
Jake Stoeffler

Reputation: 2885

Here's an idea.

$arr = array('00', '01', '02');
$randInt = rand(1, 10);

if ($randInt <= 8) {
    $value = $arr[0];
}
else if ($randInt == 9) {
    $value = $arr[1];
}
else { // ($randInt == 10)
    $value = $arr[2];
}

There is now an 80% chance that $value contains '00', a 10% chance that it contains '01', and a 10% chance it contains '02'. This may not be the most efficient solution, but it will work.

Upvotes: 0

Related Questions