I need to shuffle an array so that all array elements should change their location. Given an array [0,1,2,3] it would be ok to get [1,0,3,2] or [3,2,0,1] but not [3,1,2,0].
Is there any function in python to do this or I have to do this myself?
I need to shuffle an array so that all array elements should change their location. Given an array [0,1,2,3] it would be ok to get [1,0,3,2] or [3,2,0,1] but not [3,1,2,0].
Is there any function in python to do this or I have to do this myself?
The shortest solution I can think of would be to use random.shuffle(v)
to shuffle and check the result until all elements are in a different location:
while not allDifferent(v):
random.shuffle(v)
The risk of this is of course that you may potentially have to try many times, but that is not a very big problem. After running some tests on this, the average number of attempts before all elements are in a different position is about 3 for list length 3. 2.7 for list length 5, and then it seems to stay around 2.7 for longer lists (tried up to length 1000).
It's a bit iffy to rely on the probability like that, but for most applications you should be fine.
Edit: Now if you would prefer something faster, you would probably have to do it yourself. Something like this:
for i in range(0, len(a)-1):
pick = random.randint(i+1, len(a)-1)
a[i], a[pick] = a[pick], a[i]
That one will shuffle the array so that no number ends up in the same place as before (because of the i+1
).