Given an integer array shuffle the elements in the array such that no two elements are in same place.
After shuffling all elements should be difference place when compared to original array.
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?
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?
@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 :-)
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??
that algorithm has a name, https://en.wikipedia.org/wiki/Fisher–Yates_shuffle
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.