Input: a sequence, which can be a group of numbers, such as 1, 2, 3, 4..., or a group of strings "111", "222 ",....
Output: randomization sequence of the original sequence
Requirement: the probability of occurrence of each random sequence is equal. For example, if the input is {1, 2, 3}, there are 6 types of randomization sequences, which must be output, however, the probability of each random sequence output is 1/6.
Main Methods:
For {1, 2, 3}, first fix 3 and switch 1, 2, with {1, 2}, {2, 1, 3 }, then, the three in each group are exchanged with any of these data sets, and six sequences are finally obtained. Based on the probability multiplication formula, each
The probability of sequence occurrence is 1/6.
For {1, 2, 3, 4}, 4 is fixed, and the previous {1, 2, 3} has been randomized to six sequences. Then, according to the previous method, 4 is exchanged with all the data in each group, finally, we can get 24 random sequences, each of which
The probability of occurrence of a sequence is 1/24.
Other analogy
Generic programming technology should be used to consider the universality of the program.
Code:
# Include <iostream> # include <vector> # include <algorithm> # include <ctime> # include <iterator> using namespace STD; const int n = 10; template <class iterator> void myrandom_shuffle (iterator beg, iterator end) {iterator it; srand (unsigned (time (0); int diff; iterator SWP; for (IT = beg + 1; it! = End; it ++) {diff = rand () % (IT-Beg + 1); SWP = beg + diff; swap (* It, * SWP );}} typedef int type; Template <class iterator> inline static void output (iterator beg, iterator end) {copy (beg, end, ostream_iterator <type> (cout ,""));} void main () {vector <type> V; int I; cout <"written by wangzhicheng" <Endl; cout <"original sequence:" <Endl; for (I = 0; I <n; I ++) {v. push_back (I + 1);} output (v. begin (), V. end (); cout <Endl; myrandom_shuffle (v. begin (), V. end (); cout <"sequence after mixed washing:" <Endl; output (v. begin (), V. end (); cout <Endl ;}
Test: