Skip to content
This repository has been archived by the owner on Dec 11, 2020. It is now read-only.

Commit

Permalink
Merge pull request #1060 from vlakoff/randomElements-2
Browse files Browse the repository at this point in the history
Add allowDuplicates option to randomElements()
  • Loading branch information
fzaninotto authored Oct 20, 2016
2 parents a7ae722 + 6646f35 commit 409c90a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/Faker/Provider/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,18 +161,19 @@ public static function randomAscii()
/**
* Returns randomly ordered subsequence of $count elements from a provided array
*
* @param array $array Array to take elements from. Defaults to a-f
* @param integer $count Number of elements to take.
* @param array $array Array to take elements from. Defaults to a-f
* @param integer $count Number of elements to take.
* @param boolean $allowDuplicates Allow elements to be picked several times. Defaults to false
* @throws \LengthException When requesting more elements than provided
*
* @return array New array with $count elements from $array
*/
public static function randomElements(array $array = array('a', 'b', 'c'), $count = 1)
public static function randomElements(array $array = array('a', 'b', 'c'), $count = 1, $allowDuplicates = false)
{
$allKeys = array_keys($array);
$numKeys = count($allKeys);

if ($numKeys < $count) {
if (!$allowDuplicates && $numKeys < $count) {
throw new \LengthException(sprintf('Cannot get %d elements, only %d in array', $count, $numKeys));
}

Expand All @@ -182,11 +183,14 @@ public static function randomElements(array $array = array('a', 'b', 'c'), $coun

while ($numElements < $count) {
$num = mt_rand(0, $highKey);
if (isset($keys[$num])) {
continue;

if (!$allowDuplicates) {
if (isset($keys[$num])) {
continue;
}
$keys[$num] = true;
}

$keys[$num] = true;
$elements[] = $array[$allKeys[$num]];
$numElements++;
}
Expand Down
4 changes: 4 additions & 0 deletions test/Faker/Provider/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -547,5 +547,9 @@ public function testRandomElements()
$this->assertContains('foo', $shuffled);
$this->assertContains('bar', $shuffled);
$this->assertContains('baz', $shuffled);

$allowDuplicates = BaseProvider::randomElements(array('foo', 'bar'), 3, true);
$this->assertCount(3, $allowDuplicates);
$this->assertContainsOnly('string', $allowDuplicates);
}
}

0 comments on commit 409c90a

Please sign in to comment.