c++ - How do I print out vectors in different order every time -
i'm trying make 2 vectors. vector1 (total1) containing strings , vector2(total2) containing random unique numbers(that between 0 , total1.size() - 1)
i want make program print out total1s strings, in different order every turn. don't want use iterators or because want improve problem solving capacity.
here specific function crash program.
(unsigned = 0; < total1.size();) { v1 = rand() % total1.size(); (unsigned s = 0; s < total1.size(); ++s) { if (v1 == total2[s]) ; else { total2.push_back(v1); ++i; } } }
i'm grateful can get!
can suggest change of algorithm?. because, if current 1 correctly implemented ("s", in code, must go 0 total2.size not total1.size , if element found, break , generate new random), has following drawback: assume vectors of 1.000.000 elements , trying last random number. have 1 probability in 1.000.000 of find random number not used. small amount.last 1 number has probability of 2 in 1.000.000 small. in conclusion, program loop , expend lots of cpu resources.
your best alternative follow @nathanoliver suggestion , function std::shuffle
. manual page shows implementation algorithm, looking for.
another simple algorithm, pros , cons, is:
- init total2 sequence 0,1,2,...,n n size total1 - 1
- choice 2 random numbers, i1 , i2, in range [0,n-1].
- swap elements i1 , i2 in total2.
- repeat (2) fixed number of times "r".
this method allows known priori necessary steps , control level of "randomness" of final vector (bigger r more random). however, far in randomness quality.
another method, better in probabilistic distribution:
- fill list
l
number 0,1,2,...size total1-1. - choice random number
i
between 0 , size of listl
- 1 . - store in total2
i
-th element in listl
. - remove element
l
. - repeat (2) until
l
empty.
Comments
Post a Comment