This article will show you how to generate a random, non-repeating array (or a list). Of course, the number to be filled is an integer.
Let's take a look at how to implement it:
# Include <iostream> # include <algorithm> a [(I =; I <; I ++ a [I] = * a_begin = * a_end = a + () /(j =; j <; j ++ cout <a [j] <}Test_Random.cpp
1. First create an array object a []. Of course, you can also use double or other types of arrays as needed.
2. assign an initial value to the array. In the code, the for loop directly assigns 1 ~ to each element in ~ An integer of 1000.
3. Use random_shuffle Gaussian to randomly disrupt the elements in the array, which generates a random array. If you want to make it messy, you can call random_shuffle multiple times to perform the operation.
4. Show the random array to view the effect.
Q: What if I want to generate a variable-length random series?Is the following method feasible?
int main() { int* a = null; a = new int[1000];for(int i=0;i<1000;i++){a[i] = i;}int* a_begin = a; int* a_end = a + sizeof(a)/sizeof(int); random_shuffle(a_begin,a_end); for(int j=0; j<1000; j++) { cout<<a[j]<<"\t"; } getchar();return 0;}
Note: If you are interested in the above Code, please try it as much as you can, so you don't have to worry that your friends are stunned!
Solution: To generate a variable-length random sequence, what is the correct and feasible Solution?
# Include <iostream> # include <vector> # include <algorithm> vector <> (I =; I <; I ++ (j =; j <. size (); j ++ cout <a [j] <(! A. swap (vector <>}TestRandom2.cpp
1. First create vector <> Object a. Of course, double or other types can be used as needed.
2. Insert 1000 elements in a for loop. The value range is 1 ~ 1000.
3. Use random_shuffle Gaussian to randomly disrupt the elements in the array, which generates a random array. If you want to make it messy, you can call random_shuffle multiple times to perform the operation.
4. Show the random array to view the effect.
5. Clear the vector at the end <>.