Given an integer array shuffle the elements in the array such that no two elements are in same place.

• Given an integer array shuffle the elements in the array such that no two elements are in same place.

• I don't understand. How could two elements be in the same place?

• After shuffling all elements should be difference place when compared to original array.

• Ok, that makes more sense. But what about the "no two elements"?

• From my understanding, the question is: "Given an integer array, shuffle the elements such that no element in the shuffled array is at the same position as in the original array."

"no two elements" means one element is from the shuffled array, and the other is from the original array, is that correct @ramya2?

• I guess this works?

``````def shuffle(a):
a[:] = a[1:] + a[:1]``````

• Or for a random one:

``````import random
def shuffle(a):
i = range(len(a))
while any(j == k for j, k in enumerate(i)):
random.shuffle(i)
a[:] = [a[j] for j in i]
``````

• Hi @StefanPochmann, I found this interesting article about array shuffle, it has nice animation, take a look at the last method, is it the same as your random solution?

http://bost.ocks.org/mike/shuffle/

• @jeantimex Very nice animations... But no, that's not what I'm doing, as it doesn't ensure that no element ends up at its original spot. Well, it might be what I'm getting done every time I call `random.shuffle(i)`. But I keep shuffling until the desired outcome is reached, i.e., no element ends up at its original spot.

Btw, I was rather surprised that you asked that, but I just checked and saw you're apparently only coding in Java, so I guess you don't understand Python? If so, I highly recommend learning it, it's fun :-)

• My Python knowledge is rather limited, and I am still learning it :) I am more a front-end engineer, JavaScript and CSS are my favorites, and I only use Java to study algorithm problems for fun, and that's why I always forgot startsWith(), lol.

• would it be possible to create a map of original index and value;

then use backtracking push a number at pos .. except for the value denoted in the map;

or something like that??

• Swap every two elements in a loop.
O(n), O(1)

• ``````public static int[] ShuffleDeck(int[] deck)
{

for(int i = 0;i< deck.Length;i++)
{
Random random = new Random(i);
int iRand = random.Next(deck.Length);
int temp = deck[i];
deck[i] = deck[iRand];
deck[iRand] =temp;
}

return deck;
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.