Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomize a sorted list?

Tags:

c++

random

theory

Here's a strange question for you guys,

I have a nice sorted list that I wish to randomize. How would i go about doing that?

In my application, i have a function that returns a list of points that describe the outline of a discretized object. Due to the way the problem is solved, the function returns a nice ordered list. i have a second boundary described in math and want to determine if the two objects intersect each other. I simply itterate over the points and determine if any one point is inside the mathematical boundary.

The method works well but i want to increase speed by randomizing the point data. Since it is likely that that my mathematical boundary will be overlapped by a series of points that are right beside each other, i think it would make sense to check a randomized list rather than iterating over a nice sorted one (as it only takes a single hit to declare an intersection).

So, any ideas on how i would go about randomizing an ordered list?

like image 891
Faken Avatar asked Apr 22 '10 16:04

Faken


People also ask

How do you randomize a sort in Excel?

To do a random sort in Excel, use the RAND Function and then the Sort feature to shuffle a list randomly. To the right of the column of data to be randomized, click in the first cell and type in the RAND Function.

How do you randomize a list in Python?

To use shuffle, import the Python random package by adding the line import random near the top of your program. Then, if you have a list called x, you can call random. shuffle(x) to have the random shuffle function reorder the list in a randomized way. Note that the shuffle function replaces the existing list.

How do you randomize a list in Excel without duplicates?

Select random rows in Excel without duplicates Only works in Excel 365 and Excel 2021 that support dynamic arrays. To select random rows with no repeats, build a formula in this way: INDEX(SORTBY(data, RANDARRAY(ROWS(data))), SEQUENCE(n), {1,2,…}) Where n is the sample size and {1,2,…} are column numbers to extract.


3 Answers

Use std::random_shuffle. If you want to implement the method yourself you should look at the Fisher-Yates shuffle.

like image 131
pmr Avatar answered Oct 15 '22 20:10

pmr


You can try the random_shuffle algorithm, but note that it won't work on list since it requires random access iterators. You can use it on a vector or deque, though.

like image 34
Fred Larson Avatar answered Oct 15 '22 20:10

Fred Larson


Assuming your "list" doesn't mean a linked list, but instead means something that supports random access (e.g., an array, std::vector, or std::deque), std::random_shuffle might be useful.

like image 1
Jerry Coffin Avatar answered Oct 15 '22 20:10

Jerry Coffin