Skip to content

Commit

Permalink
Merge pull request #266 from boesing/qa/shuffle-fisher-yates
Browse files Browse the repository at this point in the history
Allow random permutations without restrictions
  • Loading branch information
boesing committed Aug 22, 2024
2 parents 45d2d46 + afa6dac commit 1e3e8b7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
5 changes: 1 addition & 4 deletions src/OrderedList.php
Original file line number Diff line number Diff line change
Expand Up @@ -482,10 +482,7 @@ public function shuffle(): OrderedListInterface

$data = $this->data;

do {
shuffle($data);
} while ($this->data === $data);

shuffle($data);
$instance = clone $this;
$instance->data = $data;

Expand Down
32 changes: 24 additions & 8 deletions tests/GenericOrderedListTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use function mt_rand;
use function range;
use function spl_object_hash;
use function sprintf;
use function strlen;
use function strnatcmp;

Expand Down Expand Up @@ -1476,16 +1477,31 @@ public function testWillRemoveItemAtSpecificPosition(): void

public function testWillShuffleValuesInList(): void
{
$list = new GenericOrderedList([
1,
2,
3,
]);
$values = [1, 2, 3];
$list = new GenericOrderedList($values);

$maximumShuffleAttempts = 10;
$shuffledSameCount = 0;

do {
$list2 = $list->shuffle();
/** @psalm-suppress TypeDoesNotContainType No clue why this is happening but for now we are suppressing */
if ($list2->toNativeArray() === $values) {
$shuffledSameCount++;
self::assertLessThan(
$maximumShuffleAttempts,
$shuffledSameCount,
sprintf('The shuffle did not change the order after "%d" attempts.', $maximumShuffleAttempts),
);
continue;
}

break;
} while ($shuffledSameCount < $maximumShuffleAttempts);

$list2 = $list->shuffle();
self::assertSame([1, 2, 3], $list->toNativeArray());
self::assertNotSame($list, $list2);
self::assertNotSame([1, 2, 3], $list2->toNativeArray());
self::assertEqualsCanonicalizing($values, $list2->toNativeArray());
self::assertNotSame($values, $list2->toNativeArray());
}

public function testWillCombineWithAnohterList(): void
Expand Down

0 comments on commit 1e3e8b7

Please sign in to comment.