Supposing I have two arrays which are identical:
var array1=[1,2,3,4,5], array2=[1,2,3,4,5]
How do I shuffle the second array such that no elements are in the same position as in the first array:
array2=[3,1,4,5,2] // OK
array2=[1,4,2,3,5] // Not OK
I was able to achieve the desired result by using a while loop and a custom "shuffle" and a "same_position" function:
shuffle(array2)
while(same_position(array1,array2)){
shuffle(array2);
}
function same_position(array1,array2){
// checks with a loop whether any elements are in the same position in array 1 and array 2, returns true if so
}
function shuffle(array){
// randomly shuffles array in place
}
However, I wonder whether there is a more efficient way of doing this without using nested loops - is it possible to achieve the same result in a single pass?