i am looking to to write script that will pull variables based on percentages.
for example ...
30% of the time, var1 = 1;
20% of the time, var1 = 2;
50% of the time, var1 = 3;
i'm really not sure how to implement this.
any ideas?
| SitePoint Sponsor |


i am looking to to write script that will pull variables based on percentages.
for example ...
30% of the time, var1 = 1;
20% of the time, var1 = 2;
50% of the time, var1 = 3;
i'm really not sure how to implement this.
any ideas?
_________________________





Maybe something like this:
PHP Code:function percentRandom()
{
$rand=rand(0,100);
if($rand<=20) //0-20
{
return 2;
}
if($rand<=50) //21-50
{
return 1;
}
return 3; //51-100
}
$var=percentRandom();




PHP Code:$n = rand(1, 100);
if ($n <= 30)
$var1 = 1;
elseif (30 < $n && $n <= 50)
$var1 = 2;
else
$var1 = 3;




youngtwig was faster
although his script has a minor mistake:
since rand($min, $max) returns a number between $min and $max inclusive, rand(0, 100) actually returns 101 possible values, meaning that number 2 will occur more often (in 21 of 101 tries) than in 20% of the time. But since the difference is really small, this could be called hairsplitting![]()


wow guys ... you rock ... i'll be trying this shortly
almost at that part
_________________________

theres always this way too
PHP Code:
$num = mtrand(0, 100);
switch ($num <= 20 | ($num > 20 && $num <= 50) | ($num > 50 && $num <= 100)) {
case (true | false | false):
//20% of the time, $var1 is 1
$var1 = 1;
break;
case (false | true | false):
//30% of the time, $var1 is 2
$var1 = 2;
break;
case (false | false | true):
//50% of the time, $var1 is 3
$var1 = 3;
break;
}


both repped.
so simple!
_________________________




picasso-trigger, glad we helped
altecex, I've never seen such switch-statement syntax ... Even though I understand it, it seems too confusing to me.
Also, you have made the same mistake as youngtwig - you pick your number between 0 and 100 (inclusive) to get 100 possible return values, but you get 101 and your distribution of resulting numbers is slighly off balance :P
/slap me
don't I have anything better to do then to poke people and split hair?
Best regards





As long as it's not Hehir-splitting.Originally Posted by dbevfat
![]()
Bookmarks