C + + generates 54 different random numbers __c++

Source: Internet
Author: User
Tags random seed

A function that uses C + + to generate different random numbers rand () is supplemented by the Srand () function to generate 54 digits between 0~53 (54 is chosen because of the shuffle)

Algorithm one: To first define an array (which can be all 0 or the same number or no value), start by using the Srand () function to generate a random seed, using the rand () function to generate random numbers, starting with the first number into the array, each comparing to the previous i-1 If they have the same, they can be rebuilt and judged; The implementation code is as follows:

</pre><pre name= "code" class= "HTML" ><span style= "font-family:arial, Helvetica, Sans-serif;" >int Main () </span>
{
	int a[54];
	Srand ((unsigned) time (NULL));
	for (int i = 0; i < i++)
	{
		A[i] = rand ()%;
		int j = i;
		while (j--) {
			if (a[i] = = A[j])
			{
				A[i] = rand ()%;
				j = i;
			}
		}
		cout << a[i] << ';
	}
		cout << Endl;
		System ("pause");
		return 0;
}
Algorithm 2: The use of C++STL container and algorithm to first define a container to accommodate the 0~53 54 digits, stored in ascending order, and then use the Random_shuffle () function to disrupt, and then output can get 54 different random number, the implementation code as follows:

int main ()
{
	vector<int>vi;
	for (int i = 1; I <= i++) {
		vi.push_back (i);
	}
	Vector<int>::iterator it1 = Vi.begin ();
	while (it1!= vi.end ()) {
		cout << *it1<< ';
		it1++;
	}
	cout << Endl;
	Random_shuffle (Vi.begin (), Vi.end ());
	Vector<int>::iterator it2 = Vi.begin ();
	while (It2!= vi.end ()) {
		cout << *it2 << ';
		it2++;
	}
	cout << Endl;
	System ("pause");
	return 0;
}
These are two simple algorithms and implementation codes for generating random numbers


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.