For an online game I create an initial PHP array with 36 values: A-Z 0-9. A random script remix the array, i.e
[0] R
[1] 4
[2] N
[3] d
...
[35] 8
Once done the script assigns 6 signs to each of the 6 players via a chunk($arr,6)
.
Player 1 [0] = [R,4,n,d,O,M]
Player 2 [1] = [p,2,s,Z,k,u]
...
Player 6 [5] = [J,r,V,5,z,8]
The question is: once the table of players has been reordered alphabetically, is there an algorithmic way to recreate the initial distribution?
To simplify the question:
Initial array
[0] = abc
[1] = def
[2] = ghi
[3] = jkl
[4] = mno
[5] = pqr
Random order permutation [0,1,2,3,4,5] -> [2,5,0,3,1,4]:
[2] = ghi
[5] = pqr
[0] = abc
[3] = jkl
[1] = def
[4] = mno
Result:
new order [0] [1] [2] [3] [4] [5]
value ghi pqr abc jkl def mno
former order [2] [5] [0] [3] [1] [4] -> random permutation
To retrieve former order I must find the way to produce the array [2,4,0,3,5,1]:
new order [2] [4] [0] [3] [5] [1]
value abc def ghi jkl mno pqr -> initial array order
How to obtain this array [2,4,0,3,5,1] from random permutation [2,5,0,3,1,4] ?
2
Answers
Yes, there is a way to do that. Let’s assume that you have an array called
$array
and you shuffle it inside afunction
to which (very important!) you pass your array by value rather than by address. Example:Output example: