[面试备忘]随机数生成

题目描述: 给定位数n(n >= 0 && n <= 10),生成n位随机数,随机数内无重复数字.

 隐含条件:最高位不能为0

 1 #include <iostream>
2 #include <time.h>
3 #include <set>
4 #include <vector>
5
6 bool randNumber(int n, unsigned long& result)
7 {
8 if (n <= 0 || n > 10) {
9 return false;
10 }
11 std::vector<int> readyNum(n);
12 std::set<int> existNum;
13 readyNum.at(n - 1) = 1 + rand() % 9;
14 existNum.insert(readyNum.at(n -1));
15 for (int index = 0; index != n - 1; ++index) {
16 while (true) {
17 int tempNum = rand() % 10;
18 if (existNum.count(tempNum)) {
19 continue;
20 }
21 readyNum.at(index) = tempNum;
22 existNum.insert(tempNum);
23 break;
24 }
25 }
26 result = 0;
27 for (int index = 0, factor = 1; index != n; ++index, factor *= 10) {
28 result += (readyNum.at(index) * factor);
29 }
30 return true;
31 }
32
33 bool randNumberFaster(int n, unsigned long& result)
34 {
35 if (n <= 0 || n > 10) {
36 return false;
37 }
38 std::vector<int> readyNum(n);
39 std::vector<int> aviableNum;
40 for (int index = 0; index!= 10; ++index)
41 {
42 aviableNum.push_back(index);
43 }
44 readyNum.at(n - 1) = 1 + rand() % 9;
45 aviableNum.at(readyNum.at(n - 1)) = -1;
46 for (int index = 0; index != n - 1; ++index) {
47 int tempIndex = rand() % 10;
48 while (true) {
49 if (-1 == aviableNum.at(tempIndex)) {
50 tempIndex = (tempIndex + 1) % 10;
51 continue;
52 }
53 readyNum.at(index) = aviableNum.at(tempIndex);
54 aviableNum.at(tempIndex) = -1;
55 break;
56 }
57 }
58 result = 0;
59 for (int index = 0, factor = 1; index != n; ++index, factor *= 10) {
60 result += (readyNum.at(index) * factor);
61 }
62 return true;
63
64 }
65 int main(int argc, _TCHAR* argv[])
66 {
67 srand(static_cast<unsigned int>(time(NULL))); unsigned long result = 0;
68 if (randNumber(10, result)) {
69 std::cout << result << std::endl;
70 }
71 if (randNumberFaster(10, result)) {
72 std::cout << result << std::endl;
73 }
74 return 0;
75 }

方法2较方法1速度上有提升,特别是在位数接近10的时候.

posted @ 2011-08-24 15:37  lifengzhong  阅读(205)  评论(0编辑  收藏  举报