Skip to content

Commit

Permalink
Fix shuffle with keys
Browse files Browse the repository at this point in the history
  • Loading branch information
miguilimzero committed Oct 6, 2022
1 parent 977e36f commit 74c5a27
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 4 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/vendor/
/tests/cache/
5 changes: 2 additions & 3 deletions src/AntiBotLinks.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,8 @@ public function generateLinks(int $amount = 4): array
{
return Cache::remember($this->identifierHash, $this->expiresIn, function () use ($amount) {
// Randomly get set of words and randomize it words order
$universe = collect(collect($this->wordUniverse)->random())
->shuffle()
->slice(0, $amount);
$words = collect($this->wordUniverse)->random();
$universe = collect($this->getRandomShuffled((array) $words, $amount));

// 50% of chance to flip solution/answers
if (random_int(0, 1)) {
Expand Down
25 changes: 25 additions & 0 deletions src/Traits/HasHelpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,29 @@ protected function asset(string $path): string
{
return __DIR__ . '/../../assets/' . $path;
}

/*
* Get random set of values from a shuffled with keys array.
*/
protected function getRandomShuffled(array $array, int $amount): array
{
return array_slice($this->shuffleWithKeys($array), 0, $amount, true);
}

/**
* Shuffle array without loosing keys.
*/
protected function shuffleWithKeys(array $array): array
{
$keys = array_keys($array);

shuffle($keys);

$new = [];
foreach ($keys as $key) {
$new[$key] = $array[$key];
}

return $new;
}
}
1 change: 0 additions & 1 deletion tests/cache/a0/ec/a0ec9f844aeebab14f0302a2edf0920035bcfc0a

This file was deleted.

0 comments on commit 74c5a27

Please sign in to comment.