Skip to content

Commit 1e3e8b7

Browse files
authored
Merge pull request #266 from boesing/qa/shuffle-fisher-yates
Allow random permutations without restrictions
2 parents 45d2d46 + afa6dac commit 1e3e8b7

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

src/OrderedList.php

+1-4
Original file line numberDiff line numberDiff line change
@@ -482,10 +482,7 @@ public function shuffle(): OrderedListInterface
482482

483483
$data = $this->data;
484484

485-
do {
486-
shuffle($data);
487-
} while ($this->data === $data);
488-
485+
shuffle($data);
489486
$instance = clone $this;
490487
$instance->data = $data;
491488

tests/GenericOrderedListTest.php

+24-8
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
use function mt_rand;
2929
use function range;
3030
use function spl_object_hash;
31+
use function sprintf;
3132
use function strlen;
3233
use function strnatcmp;
3334

@@ -1476,16 +1477,31 @@ public function testWillRemoveItemAtSpecificPosition(): void
14761477

14771478
public function testWillShuffleValuesInList(): void
14781479
{
1479-
$list = new GenericOrderedList([
1480-
1,
1481-
2,
1482-
3,
1483-
]);
1480+
$values = [1, 2, 3];
1481+
$list = new GenericOrderedList($values);
1482+
1483+
$maximumShuffleAttempts = 10;
1484+
$shuffledSameCount = 0;
1485+
1486+
do {
1487+
$list2 = $list->shuffle();
1488+
/** @psalm-suppress TypeDoesNotContainType No clue why this is happening but for now we are suppressing */
1489+
if ($list2->toNativeArray() === $values) {
1490+
$shuffledSameCount++;
1491+
self::assertLessThan(
1492+
$maximumShuffleAttempts,
1493+
$shuffledSameCount,
1494+
sprintf('The shuffle did not change the order after "%d" attempts.', $maximumShuffleAttempts),
1495+
);
1496+
continue;
1497+
}
1498+
1499+
break;
1500+
} while ($shuffledSameCount < $maximumShuffleAttempts);
14841501

1485-
$list2 = $list->shuffle();
1486-
self::assertSame([1, 2, 3], $list->toNativeArray());
14871502
self::assertNotSame($list, $list2);
1488-
self::assertNotSame([1, 2, 3], $list2->toNativeArray());
1503+
self::assertEqualsCanonicalizing($values, $list2->toNativeArray());
1504+
self::assertNotSame($values, $list2->toNativeArray());
14891505
}
14901506

14911507
public function testWillCombineWithAnohterList(): void

0 commit comments

Comments
 (0)