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:

  1. init total2 sequence 0,1,2,...,n n size total1 - 1
  2. choice 2 random numbers, i1 , i2, in range [0,n-1].
  3. swap elements i1 , i2 in total2.
  4. 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:

  1. fill list l number 0,1,2,...size total1-1.
  2. choice random number i between 0 , size of list l - 1 .
  3. store in total2 i-th element in list l.
  4. remove element l.
  5. repeat (2) until l empty.

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -