Esempio n. 1
0
 public function testWeightedChoiceWithNonIntegerWeights()
 {
     $weights = ['a' => 0.15, 'b' => 0.15, 'c' => 0.1, 'd' => 0.4, 'e' => 0.2];
     $pairs = a\pairs($weights);
     $appearances = array_fill_keys(array_keys($weights), 0);
     for ($i = 0; $i < 50000; ++$i) {
         ++$appearances[weightedChoice($pairs)];
     }
     foreach ($appearances as $item => $rate) {
         $this->assertEquals(50000 * $weights[$item], $rate, '', 300);
     }
 }
Esempio n. 2
0
File: rnd.php Progetto: ihor/Nspl
<?php

require_once __DIR__ . '/../autoload.php';
use function nspl\rnd\choice;
use function nspl\rnd\weightedChoice;
use function nspl\rnd\sample;
use function nspl\a\pairs;
// 1. Get random array element
$random = choice([1, 2, 3]);
echo sprintf("Random number is %s\n", $random);
// 2. Get 3 random numbers between 1 and 1000
$numbers = sample(range(1, 1000), 3);
echo sprintf("Three random numbers between 1 and 1000 are: %s\n", implode(', ', $numbers));
// 3. Get lottery winner, changes are proportional to number of tickets bought
// When data is presented in pairs [user_name, tickets_number]
$winner = weightedChoice([['Jack', 1], ['John', 3], ['Tom', 2]]);
echo sprintf("Lottery winner is %s (data was presented in pairs)\n", $winner);
// When data is presented in a dictionary array(user_name => tickets_number)
$winner = weightedChoice(pairs(array('Jack' => 1, 'John' => 3, 'Tom' => 2)));
echo sprintf("Lottery winner is %s (data was presented as a dictionary)\n", $winner);
Esempio n. 3
0
File: ATest.php Progetto: ihor/Nspl
 public function testPairs()
 {
     $this->assertEquals([[0, 'a'], [1, 'b'], [2, 'c']], pairs(['a', 'b', 'c']));
     $this->assertEquals([['a', 'hello'], ['b', 'world'], ['c', 42]], pairs(array('a' => 'hello', 'b' => 'world', 'c' => 42)));
     $this->assertEquals([], pairs([]));
     $this->assertEquals([[0, 'a'], [1, 'b'], [2, 'c']], call_user_func(pairs, ['a', 'b', 'c']));
     $this->assertEquals([['a', 'hello'], ['b', 'world'], ['c', 42]], call_user_func(pairs, array('a' => 'hello', 'b' => 'world', 'c' => 42)));
     $this->assertEquals([], call_user_func(pairs, []));
 }