Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/random shuffle"

From cppreference.com
< cpp‎ | algorithm
(+type reqs)
(corrected requirements (RNG here is not a RandomNumberGenerator). Renamed it to be clearer, too. Also, corrected sample implementation to honor ValueSwappable)
Line 8: Line 8:
 
}}
 
}}
 
{{ddcl list item | num=2 | notes={{mark until c++11}}<br><br><br><br>{{mark since c++11}} |
 
{{ddcl list item | num=2 | notes={{mark until c++11}}<br><br><br><br>{{mark since c++11}} |
template< class RandomIt, class RNG >
+
template< class RandomIt, class RandomFunc >
void random_shuffle( RandomIt first, RandomIt last, RNG& r );
+
void random_shuffle( RandomIt first, RandomIt last, RandomFunc& r );
  
template< class RandomIt, class RNG >
+
template< class RandomIt, class RandomFunc >
void random_shuffle( RandomIt first, RandomIt last, RNG&& r );
+
void random_shuffle( RandomIt first, RandomIt last, RandomFunc&& r );
 
}}
 
}}
 
{{ddcl list item | num=3 | notes={{mark since c++11}} |
 
{{ddcl list item | num=3 | notes={{mark since c++11}} |
Line 33: Line 33:
 
{{param list begin}}
 
{{param list begin}}
 
{{param list item | first, last | the range of elements to shuffle randomly}}
 
{{param list item | first, last | the range of elements to shuffle randomly}}
{{param list item | r | function object returning a randomly chosen value of type {{tt|iterator_traits<RandomIt>::difference_type}} in the interval [0,n) if invoked as {{tt|r(n)}} }}
+
{{param list item | r | function object returning a randomly chosen value of type convertible to  {{tt|iterator_traits<RandomIt>::difference_type}} in the interval [0,n) if invoked as {{tt|r(n)}} }}
{{param list item | g | function object returning a randomly chosen value of type {{tt|URNG::result_type}} in the interval [g.min(), g.max()] if invoked as {{tt|g()}} (intended to be used with uniform random number generators from the standard library) }}
+
{{param list item | g | function object returning a randomly chosen value of type {{tt|URNG::result_type}} in the interval [g.min(), g.max()] if invoked as {{tt|g()}} (e.g. any of the uniform random number generators from {{tt|<random>}}) }}
 
{{param list hreq}}
 
{{param list hreq}}
{{param list req concept | RandomIt | RandomAccessIterator}}
+
{{param list req concept | RandomIt | RandomAccessIterator | ValueSwappable}}
{{param list req concept | RNG | RandomNumberGenerator}}
+
 
{{param list req concept | URNG | UniformRandomNumberGenerator}}
 
{{param list req concept | URNG | UniformRandomNumberGenerator}}
 
{{param list end}}
 
{{param list end}}
Line 51: Line 50:
 
{{eq fun
 
{{eq fun
 
  | 1=
 
  | 1=
template<class RandomIt, class RandomNumberGenerator>
+
template<class RandomIt, class RandomFunc>
void random_shuffle(RandomIt first, RandomIt last,  
+
void random_shuffle(RandomIt first, RandomIt last, RandomFunc&& r)
                    RandomNumberGenerator&& r)
+
 
{
 
{
 
     typename std::iterator_traits<RandomIt>::difference_type i, n;
 
     typename std::iterator_traits<RandomIt>::difference_type i, n;
 
     n = last - first;
 
     n = last - first;
 
     for (i = n-1; i > 0; --i) {
 
     for (i = n-1; i > 0; --i) {
         std::swap(first[i], first[r(i+1)]);
+
         using std::swap;
 +
        swap(first[i], first[r(i+1)]);
 
     }
 
     }
 
}
 
}
Line 74: Line 73:
 
     diff_t n = last - first;
 
     diff_t n = last - first;
 
     for (diff_t i = n-1; i > 0; --i) {
 
     for (diff_t i = n-1; i > 0; --i) {
         std::swap(first[i], first[D(g, param_t(0, i))]);
+
         using std::swap;
 +
        swap(first[i], first[D(g, param_t(0, i))]);
 
     }
 
     }
 
}
 
}

Revision as of 12:42, 28 August 2012

 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy, ranges::sort, ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
(C++11)                (C++11)(C++11)

Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
random_shuffleshuffle
(until C++17)(C++11)
(C++20)(C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
 

Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <algorithm>
</td>

<td></td> <td></td> </tr> <tr class="t-dcl ">

<td >
template< class RandomIt >
void random_shuffle( RandomIt first, RandomIt last );
</td>

<td > (1) </td> <td class="t-dcl-nopad"> </td> </tr> <tr class="t-dcl ">

<td >
template< class RandomIt, class RandomFunc >

void random_shuffle( RandomIt first, RandomIt last, RandomFunc& r );

template< class RandomIt, class RandomFunc >

void random_shuffle( RandomIt first, RandomIt last, RandomFunc&& r );
</td>

<td > (2) </td> <td > (until C++11)



(since C++11) </td> </tr> <tr class="t-dcl ">

<td >
template< class RandomIt, class URNG >
void shuffle( RandomIt first, RandomIt last, URNG&& g );
</td>

<td > (3) </td> <td > (since C++11) </td> </tr> Template:ddcl list end

Reorders the elements in the given range [first, last) such that each possible permutation of those elements has equal probability of appearance.

1) The random number generator is implementation-defined, the function std::rand is often used.
2) The random number generator is the function object r.
3) The random number generator is the function object g.

Contents

Parameters

first, last - the range of elements to shuffle randomly
r - function object returning a randomly chosen value of type convertible to iterator_traits<RandomIt>::difference_type in the interval [0,n) if invoked as r(n)
g - function object returning a randomly chosen value of type URNG::result_type in the interval [g.min(), g.max()] if invoked as g() (e.g. any of the uniform random number generators from <random>)
Type requirements
-
RandomIt must meet the requirements of ValueSwappable and LegacyRandomAccessIterator.
-
URNG must meet the requirements of UniformRandomNumberGenerator.

Return value

(none)

Complexity

linear in the distance between first and last

Possible implementation

First version
template<class RandomIt, class RandomFunc>
void random_shuffle(RandomIt first, RandomIt last, RandomFunc&& r)
{
    typename std::iterator_traits<RandomIt>::difference_type i, n;
    n = last - first;
    for (i = n-1; i > 0; --i) {
        using std::swap;
        swap(first[i], first[r(i+1)]);
    }
}
Second version
template<class RandomIt, class UniformRandomNumberGenerator>
void shuffle(RandomIt first, RandomIt last, 
             UniformRandomNumberGenerator&& g)
{
    typedef typename std::iterator_traits<RandomIt>::difference_type diff_t;
    typedef typename std::make_unsigned<diff_t>::type udiff_t;
    typedef typename std::uniform_int_distribution<udiff_t> distr_t;
    typedef typename distr_t::param_type param_t;
 
    distr_t D;
    diff_t n = last - first;
    for (diff_t i = n-1; i > 0; --i) {
        using std::swap;
        swap(first[i], first[D(g, param_t(0, i))]);
    }
}

Example

The following code randomly shuffles the integers 1..10

#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
 
int main()
{
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
    std::random_device rd;
    std::mt19937 g(rd());
 
    std::shuffle(v.begin(), v.end(), g);
 
    copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
}

Possible output:

8 6 10 4 2 3 7 1 9 5

See also

Template:cpp/algorithm/dcl list next permutationTemplate:cpp/algorithm/dcl list prev permutation