-1

For example I have an array like:

$items = [
    '0' => [
        'name' => 'item1', 
        'percent' => 10
        ],
    '2' => [
        'name' => 'item2', 
        'percent' => 20
        ],
    '3' => [
        'name' => 'item3', 
        'percent' => 30
        ],
    '4' => [
        'name' => 'item4', 
        'percent' => 40
        ],
];

And function:

function echoRandomItem(){
}

If I call this function it should return 'name' of the item depending on the 'percent' value. Basically if I call this function 100 times it should return item1 10 times, item2 20 times, item3 30 times, item4 40 times.

Pang
  • 9,564
  • 146
  • 81
  • 122
niQitos
  • 89
  • 1
  • 8
  • 1
    Hello, we're not developers for hire. Try to make this yourself, then if you have bugs in it, we'll be able to help you. – Olivier Grégoire Feb 14 '17 at 18:48
  • Hey man, I cannot figure out the algorithm itself and want some help to figure it out. Maybe you know some formula that may help? At first sight the task seems easy, but I cannot grasp it. – niQitos Feb 14 '17 at 18:51
  • 2
    It's called "random weighted distribution". Look for that on the Internet with the language you're using. By the way you've not even said which language you're using. – Olivier Grégoire Feb 14 '17 at 18:53
  • Ok, thanks. This is my first time here so thank you for bearing with me. By the way it's PHP – niQitos Feb 14 '17 at 18:56

1 Answers1

1

Here is a solution I've come up with thanks to Oliver's hint. $items is a given array. wrand() function is responsible for random weighted distribution calculation.

$items = [
    '1' => [
        'name' => 'item1', 
        'rand' => 10
        ],
    '2' => [
        'name' => 'item2', 
        'rand' => 20
        ],
    '3' => [
        'name' => 'item3', 
        'rand' => 30
        ],
    '4' => [
        'name' => 'item4', 
        'rand' => 40
        ],
];

function wrand($data) {

    foreach ($data as $value) {
        $itemsRand[] = $value ['rand'];
    }

    $totalw = array_sum($itemsRand);
    $rand   = rand(1, $totalw);

    $curw   = 0;
    foreach ($data as $val) {
        $curw += $val['rand'];
        if ($curw >= $rand) return $val['name'];
    }

    return end($data);
}

Further code simply calls wrand() function 100 times and counts the results.

static $item1 = 0;
static $item2 = 0;
static $item3 = 0;
static $item4 = 0;

for ($i = 0; $i < 100; $i++){
    $k = wrand($items);

    if ($k == 'item1') {
        $item1++;
    } elseif ($k == 'item2'){
        $item2++;
    } elseif ($k == 'item3'){
        $item3++;
    } elseif ($k == 'item4'){
        $item4++;
    }
}

echo "item1 = $item1<br>";
echo "item2 = $item2<br>";
echo "item3 = $item3<br>";
echo "item4 = $item4";
niQitos
  • 89
  • 1
  • 8