简体   繁体   中英

How to k-shuffle an array with STL?

I am testing an algorithm that sorts a k-sorted array (every element is at most k-positions away from its correct sorted position).

I am having a hard time generating test data -- I can't randomly swap elements by k-positions because I may end up swapping an element twice. I could track which elements I swapped but then I need O(N) space. I could also use a random-heap of size k + 1, but that sounds silly.

Is there anything built into the STL that can help me with this? This seems like a common problem, but my brief research only turned up algorithms for total shuffles (I think STL implements Fisher-Yates).

It feels odd problem since preparing random test data does not need to be ultra efficient, also the data may be usually whatever. You can have the test values as correct positions of those elements or pairs that give range of correct positions. For example array of pairs:

  1. 1,1
  2. 2,4
  3. 2,4
  4. 2,4
  5. 5,6
  6. 5,6
  7. 7,7
    ...

Store the state of random generator somewhere.

Choose two random elements whose position is not more than k positions away of original position (or range) of other and swap. Repeat that N times and your test data is ready.

If you need to get same sequence later then restore the random generator state and repeat the algorithm.

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