如何生成包含 256 个不同数字的数组
How to generate an array of 256 distinct numbers
>我有这个:
#include <iostream>
using namespace std;
int main()
{
int a[256];
int b;
int k;
for (int i = 0; i < 256; i ++){
b = rand()%256;
k = 0;
for (int j = 0; j< i; j ++)
{
if (a[j] == b){k = 1;}
}
if (k == 0){a[i] = b;}
if (k==1){i--;}
}
return 0;
}
这将生成一个从 0 到 255 的整数数组。每个整数在数组中只出现一次。我的问题是这段代码需要相当长的时间来执行,因为对于每个新的随机整数,我都会检查该整数是否已经在数组中。所以我必须等到从 0 到 255 的所有整数都显示为随机数。我的问题是:
有没有更好的方法可以做到这一点?
正如其他人提到的,使用 std::random_shuffle:
std::vector<int> my_vec(256); //Reserve space for 256 numbers in advance.
for(int n = 0; n < 256; ++n)
{
my_vec.push_back(n);
}
std::random_shuffle(my_vec.begin(), my_vec.end());
如
前所述,std::random_shuffle
是要走的路,但以防万一你不想使用它(也许使用 ANSI C 而不是 C++),这里有一个快速而肮脏的实现:
#include <stdlib.h>
#include <time.h>
#define SIZE 256
static inline void
swap(int *a, int *b) {
// Don't swap them if they happen to be the same element
// in the array, otherwise it'd be zeroed out
if (a != b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
}
int main(void)
{
int A[SIZE], i;
// Initialize array with sequential incrementing numbers
for (i = 0; i < SIZE; ++i)
A[i] = i;
// Initialize random seed
srand(time(NULL));
// Swap every element of the array with another random element
for (i = 0; i < SIZE; ++i)
swap(&A[i], &A[rand() % SIZE]);
return 0;
}
你可以尝试这样的事情:
int main()
{
std::vector<int> available(256);
int a[256];
for (int i = 0; i < 256; ++i)
available.push_back(i);
for (int i = 0; i < 256; ++i)
{
int idx = rand() % available.size();
a[i] = available[idx];
available.erase(available.begin()+idx);
}
// use a[] as needed...
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
int main(int argc, const char * argv[])
{
std::vector<int> items(256);
std::iota(items.begin(),items.end(),0);
std::random_shuffle(items.begin(), items.end());
for(auto i:items)
std::cout<<i<<" ";
}
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 数组/c++中的大量数字
- 遍历并行数组以确定C++中的最大数字
- 整数区间(或 int 数组)中每个数字的出现次数
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 获取 2D 数组 c++ 中的所有数字对
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 以十为基数的数字到布尔数组,该数组要求二进制/基数为 2 的数字
- C++ 检查结果数组中有多少次数字
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 如何在C++中有效地将数字值重新分配给字符数组
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 类、数字/数组或对象中的对象