有一个棘手的事情得到的是:让你想作为一个排列随机生成的10个值,并且希望将它们存储在一个文件中说。
所以,你可以计算出如何生成随机指标则使用索引值的阵列上存储数据:
我也面临一些同样的问题,有一天,当我开发卡的游戏的图像,每个失败的隐藏图像随机跳转到某些位置。
#include <iostream>
#include <fstream>
#include <ctime>
int main(){
srand(time(NULL));
std::ofstream out("data.txt");
// arrays of data whose values will be stored randomly in a text file.
int array[10] = {7, 57, 23, 21, 1,
0, 18, 19, 3, 777};
// array of indexes and initializing it
int indexes[10];
for(int i(0); i < 10; i++)
indexes[i] = rand() % 10;
// indexes are filled with random values from 0 to 9 but it surely contains duplicates eg:
// 3, 0, 7, 5, 2, 8, 0, 1, 0, 0
// Now I use my algorithm to discard duplicates and repeating until I get an array of unique indexes.
for(int i = 0; i < 10; i++){
for(int j(0); j < 10; j++){
if(indexes[i] == indexes[j] && i != j){
indexes[j] = rand() % 10;
i = 0;
}
}
}
// check out that the indexes are unique and no duplicates there:
std::cout << "\n\nThe random indexes: " << std::endl;
for(int i = 0; i < 10; i++)
std::cout << indexes[i] << ", ";
// writing the random values of array using the random indexes array to the file:
for(int i = 0; i < 10; i++)
out << array[indexes[i]] << ", ";
// printing the random values of the array
std::cout << "\n\nThe random values: " << std::endl;
for(int i = 0; i < 10; i++)
std::cout << array[indexes[i]] << ", ";
out.close();
std::cout << std::endl << std::endl << std::endl;
return 0;
}
输出:尝试多次运行该程序并查看结果。
// 1
The random indexes:
3, 9, 5, 1, 7, 6, 0, 4, 8, 2,
The random values:
21, 777, 0, 57, 19, 18, 7, 1, 3, 23,
// 2
The random indexes:
5, 8, 0, 1, 3, 9, 4, 2, 6, 7,
The random values:
0, 3, 7, 57, 21, 777, 1, 23, 18, 19,
// 3
The random indexes:
6, 7, 3, 1, 5, 2, 4, 9, 0, 8,
The random values:
18, 19, 21, 57, 0, 23, 1, 777, 7, 3,
我只提供了一个小例子所以,如果你想在1000个唯一值你的情况只是看0-1000作为唯一值的数组,所以你可以使用上面的算法:
1// initializing
int randValues[1000];
for(int i(0); i < 1000; i++)
randValues[i] = (rand() % 1000) + 1; // because you want to discard 0
现在得到的唯一值:
for(int i(0); i < 1000; i++){
for(int j(0); j < 1000; j++){
if(randValues[i] == randValues[j] && i != j){
randValues[j] = (rand() % 1000) + 1;
i = 0; // reset
}
}
}
我没有得到实际的问题,你想为每个用户生成一个唯一的随机数? –
“_我的主要问题是我想让程序给用户分配一个随机的ID,比如说1-1000_”并且..这里的问题在哪里?如果您想从该范围生成唯一的ID - 最简单的解决方案是记住/读取所有使用的ID,并生成ID,直到您获得一个ID,该ID不在该“使用的ID”列表中。你尝试过吗? –
你应该只调用'srand'一次。为什么你不能从'1'开始分配ID并简单地递增? – rustyx