Home | History | Annotate | Download | only in alg.random.sample
      1 //===----------------------------------------------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is dual licensed under the MIT and the University of Illinois Open
      6 // Source Licenses. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 // <algorithm>
     11 
     12 // template <class PopulationIterator, class SampleIterator, class Distance,
     13 //           class UniformRandomNumberGenerator>
     14 // SampleIterator sample(PopulationIterator first, PopulationIterator last,
     15 //                       SampleIterator out, Distance n,
     16 //                       UniformRandomNumberGenerator &&g);
     17 
     18 #include <experimental/algorithm>
     19 #include <random>
     20 #include <cassert>
     21 
     22 #include "test_iterators.h"
     23 
     24 // Stable if and only if PopulationIterator meets the requirements of a
     25 // ForwardIterator type.
     26 template <class PopulationIterator, class SampleIterator>
     27 void test_stability(bool expect_stable) {
     28   const unsigned kPopulationSize = 100;
     29   int ia[kPopulationSize];
     30   for (unsigned i = 0; i < kPopulationSize; ++i)
     31     ia[i] = i;
     32   PopulationIterator first(ia);
     33   PopulationIterator last(ia + kPopulationSize);
     34 
     35   const unsigned kSampleSize = 20;
     36   int oa[kPopulationSize];
     37   SampleIterator out(oa);
     38 
     39   std::minstd_rand g;
     40 
     41   const int kIterations = 1000;
     42   bool unstable = false;
     43   for (int i = 0; i < kIterations; ++i) {
     44     std::experimental::sample(first, last, out, kSampleSize, g);
     45     unstable |= !std::is_sorted(oa, oa + kSampleSize);
     46   }
     47   assert(expect_stable == !unstable);
     48 }
     49 
     50 int main() {
     51   test_stability<forward_iterator<int *>, output_iterator<int *> >(true);
     52   test_stability<input_iterator<int *>, random_access_iterator<int *> >(false);
     53 }
     54