Core\Random\Seeded::shuffle
Puts every value of an array in a random order with a seeded generator, so the same order comes back on every run.
You make the generator with new Core\Random\Seeded(42). The number 42 is the seed. Two generators with the same seed give the same order. This is useful when a test runs its steps in a random order: if one order fails, the same seed repeats it. shuffle returns a new list with all the values of the array. The keys of the new list start again at 0, and the array you pass in does not change. An empty array gives an empty list.
Good to know: anybody who knows the seed knows every order. For a card game with real players, use Core\Random::shuffle.
Parameters
$aarray<T>The array to reorder.
Return value
Returns array<T>. A new list of all the values, with the keys 0, 1, …. The keys of $a are not kept, and $a is unchanged.
Examples
The same seed gives the same order
<?nvs// Shows that two generators with the same seed shuffle a deck into the same order.
array<string> $deck = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];Core\Random\Seeded $first = new Core\Random\Seeded(42);Core\Random\Seeded $second = new Core\Random\Seeded(42);
// Both lines are the same.echo Core\Json::encode($first->shuffle($deck)), "\n";echo Core\Json::encode($second->shuffle($deck)), "\n";
// The first deck does not change. Its second card is still `2`.echo $deck[1], "\n";["A","6","7","5","2","4","8","9","Q","J","3","K","10"]["A","6","7","5","2","4","8","9","Q","J","3","K","10"]2Keys are not kept
<?nvs// Shows that a shuffled array gets new keys, and what happens with an empty array.
Core\Random\Seeded $generator = new Core\Random\Seeded(42);array<int> $stock = ['apples' => 4, 'pears' => 5, 'plums' => 6];
// The result is a list, so its keys are 0, 1 and 2. This prints ["0","1","2"].array<int> $shuffled = $generator->shuffle($stock);echo Core\Json::encode(Core\Arr::keys($shuffled)), "\n";
// This prints [4,5,6]. The old order is also a possible order, and this seed gives it.echo Core\Json::encode($shuffled), "\n";
// An empty array gives an empty list. This prints [].array<int> $empty = [];echo Core\Json::encode($generator->shuffle($empty)), "\n";["0","1","2"][4,5,6][]Steps in an order you can repeat
<?nvs// Shows how to run test steps in a random order that you can repeat.
// Running steps in a new order finds a step that needs another step to run first.// The seed is printed, so a failed run can be repeated in exactly the same order.array<string> $steps = ['create user', 'log in', 'add to cart', 'pay', 'log out'];int $seed = 7;Core\Random\Seeded $generator = new Core\Random\Seeded($seed);echo 'seed ', $seed, "\n";foreach ($generator->shuffle($steps) as string $step) { echo 'run: ', $step, "\n";}seed 7run: payrun: log inrun: create userrun: log outrun: add to cart