Example of a unique random value algorithm guaranteed by C language

Source: Internet
Author: User

Cache guarantee 1 ~ N random numbers output each time are different, and the code is short. For more information, see the code.

The code is as follows: Copy code
// Copyright (c) cguage.com
// E-mail: tangcraig@gmail.com
// Date: 2014-1-21
 
# Include <iostream>
# Include <map>
# Include <cmath>
# Include <iomanip>
Using namespace std;
 
Int main (){
Map <int, int> arr;
Int num = 10;
Srand (time (0 ));
 
For (int I = 0; I <10; ++ I ){
Int idx = (num> 0? Rand () % num: 0 );
Cout <(arr. find (idx) = arr. end ()? Idx: arr [idx]) <endl;
-- Num;
Arr [idx] = (arr. find (num) = arr. end ()? Num: arr [num]);
    }
 
Return 0;
}


Although some examples are implemented in C language, this algorithm can be applied to C #, java, php, and other programming languages.

Related Article

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.