Skip to content

Commit

Permalink
Added A::pickRandoms()
Browse files Browse the repository at this point in the history
  • Loading branch information
meszaros-lajos-gyorgy committed Jul 30, 2021
1 parent f8f46b9 commit a62593f
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/A.php
Original file line number Diff line number Diff line change
Expand Up @@ -335,9 +335,35 @@ public static function join(string $separator, array $data): string
// A::pickRandom([1, 2, 3, 4, 5]) -> 3
public static function pickRandom(array $data)
{
if (self::isEmpty($data)) {
return null;
}

return $data[rand(0, self::length($data) - 1)];
}

// A::pickRandoms(2, [1, 2, 3, 4, 5]) -> [5, 2]
public static function pickRandoms(int $amount = 1, array $data): array
{
if (self::isEmpty($data) || $amount <= 0) {
return [];
}

if ($amount > self::length($data)) {
$amount = self::length($data);
}

$remaining = $data;
$selected = [];
for ($i = 0; $i < $amount; $i++) {
$randomItem = self::pickRandom($remaining, 1);
$remaining = self::without($randomItem, $remaining);
$selected[] = $randomItem;
}

return $selected;
}

// A::concat([1, 2], 3, [4, 5]) -> [1, 2, 3, 4, 5]
public static function concat(...$args): array
{
Expand Down

0 comments on commit a62593f

Please sign in to comment.