【c语言随机生成数字】C语言保证每次随机值唯一算法实例

时间:2019-09-12  来源:C语言  阅读:

使用缓存保证1~n每次输出的随机数不一样,代码比较短,思路直接见代码

 代码如下 // copyright (c) cguage.com
// e-mail:tangcraig@gmail.com
// date:  2014-1-21
 
#include
#include
#include
#include
using namespace std;
 
int main() {
    map 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;
}


虽然些实例是用C语言实现的,但是此算法可以应用于C#, java, php等编程语言。

iostream>

【c语言随机生成数字】C语言保证每次随机值唯一算法实例

http://m.bbyears.com/asp/67726.html

推荐访问:c语言随机产生四则运算 c语言如何随机产生一个数
相关阅读 猜你喜欢
本类排行 本类最新