简体   繁体   中英

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.

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%.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM