ZigZagZebra
ZigZagZebra

Reputation: 1459

Randomly swap two elements in an array in c++

Is there any way to randomly swap two elements (two different index) in an array in C++? My idea is to randomly pick the first index, then randomly pick the second one till the second index is different from the first index. Then swap these two elements. I am wondering is there any better way to do this?

I think this is different from random_shuffle because each time I only want to swap two elements in the array and keep others in the original order.

Upvotes: 1

Views: 1530

Answers (2)

Kat
Kat

Reputation: 485

Here is one solution based on @MSalters suggestion:

int first = randInt(myArray.size()-1);
int second = randInt(myArray.size()-1);
while (first == second) {
    second = randInt(myArray.size()-1);
}
char firstLetter = letters[first];
char secondLetter = letters[second];
myArray[first] = secondLetter;
myArray[second] = firstLetter;

Upvotes: 0

MSalters
MSalters

Reputation: 179779

Yes, pick two numbers First from [0...N-1] and Second from [0..N-2]. If First <= Second then ++Second so Second ends up in [0...First-1] or [First+1...N-1]. No retries needed.

Example: Say you have N=10 so First runs from 0-9 inclusive. Imagine you pick First=5. You know have 9 elements left from which to pick Second, namely 0-4 and 6-9. You now pick a number 0-8 instead, and map the subrange of possible results 5-8 to 6-9 by adding one.

<= is important. If you only added 1 if First!=Second, the chances of swapping 5 and 6 would be double, and the chances of swapping 5 and 9 would be 0%.

Upvotes: 7

Related Questions