Randomly swap two elements in an array in c++ -


is there way randomly swap 2 elements (two different index) in array in c++? idea randomly pick first index, randomly pick second 1 till second index different first index. swap these 2 elements. wondering there better way this?

i think different random_shuffle because each time want swap 2 elements in array , keep others in original order.

yes, pick 2 numbers first [0...n-1] , second [0..n-2]. if first <= second ++second second ends in [0...first-1] or [first+1...n-1]. no retries needed.

example: have n=10 first runs 0-9 inclusive. imagine pick first=5. know have 9 elements left pick second, namely 0-4 , 6-9. pick number 0-8 instead, , map subrange of possible results 5-8 6-9 adding one.

<= important. if added 1 if first!=second, chances of swapping 5 , 6 double, , chances of swapping 5 , 9 0%.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -