Kalreg
Kalreg

Reputation: 941

php percentage chance for event to occur

I know it is a noob question but i am quite stuck with it so i hope you can help me.

I have an array with integers. Depending on circumstances i can have an array with 1,2,3 or 1,1,1 or 1,2,2 and so on. The important thing is that difference between values in array may be no bigger than smallest number + 2 (i can have there 1, 2, 3 but no 1, 2, 4). Now i grab max and min of array and decrement min from max. Because always the difference between max and min is 0, 1 or 2 (array values are no bigger from eachother than two) i have free possible chances:

0: - all array values are equal
1: - all array values are from range <x, x + 1>
2: - all array values are from range <x-1, x+1>

Now if i want to randomly choose values from above arrays it's quite easy. But how can i do it with percentage chance of selecting number with bigger probability than the others?

What do i mean? Consider second example, and range of values in array x-1, x+1 - let it be Array(2, 3, 4). Now i would like to have 50% chance to select 4, 30% chance to select 3 and 20% to select 2. How can i connect value of integer in array with a chance of selecting it?

I hope you can understand what I mean and you can help me.

EDIT: In other wordsif i have an array filled with values how to easily, having a range of values that is a part of all values in array select one value with more probability than the other?

Upvotes: 0

Views: 1881

Answers (2)

radalin
radalin

Reputation: 600

$rand = rand(1, 100);
if ($rand > 50) {
    //select first array
} else {
    //select the second array and so on.
}

Will the above code help?

Upvotes: 0

Matt
Matt

Reputation: 1198

I am not sure I totally understand the first part, but say you want to have a 50% chance of selecting 4, 30% chance of selecting 3 and 20% chance of selecting 2.

You just populate an integer array of length 10 with 5 4s, 3 3s and 2 2s:

int[] a=[4,4,4,4,4,3,3,3,2,2];

Now randomly choose an index between 0 and 9 with equal probability and return the number in the array at that index. This will return 4 with 50%, 3 with 30% and 2 with 20%.

Upvotes: 1

Related Questions