1
我想創建一個2D array a[5][5]
,其中沒有2個相同的數字並且沒有元素爲0(元素由函數random(70)
生成),所以我想知道如何移除零並確保沒有2個相同的數字?C++從隨機函數中移除元素
我想創建一個2D array a[5][5]
,其中沒有2個相同的數字並且沒有元素爲0(元素由函數random(70)
生成),所以我想知道如何移除零並確保沒有2個相同的數字?C++從隨機函數中移除元素
您可以使用的東西,如下
const size_t N = 5;
int a[N][N];
std::srand((unsigned int)std::time(0));
int *p = reinterpret_cast<int *>(a);
for (size_t i = 0; i < N * N; i++)
{
int x;
while (!(x = std::rand() % 70) || std::find(p, p + i, x) != p + i) {}
p[i] = x;
}
下面是一個例子
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
int main()
{
const size_t N = 5;
int a[N][N];
std::srand((unsigned int)std::time(0));
int *p = reinterpret_cast<int *>(a);
for (size_t i = 0; i < N * N; i++)
{
int x;
while (!(x = std::rand() % 70) || std::find(p, p + i, x) != p + i);
p[i] = x;
}
for (const auto &row : a)
{
for (int x : row) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
樣本輸出
66 23 32 6 18
8 31 55 10 43
39 2 28 4 56
5 58 47 46 68
59 25 26 9 50
這種方法並不需要額外的內存。其他方法是使用std::bitset
。例如
const size_t N = 5;
int a[N][N];
std::bitset<70> b;
b.set(0);
std::srand((unsigned int)std::time(0));
for (size_t i = 0; i < N; i++)
{
for (size_t j = 0; j < N; j++)
{
int x;
while ((x = std::rand() % 70, b[x]));
//or
//while (b[x = std::rand() % 70]);
b.set(x);
a[i][j] = x;
}
}
'random(69)+ 1'? – Lol4t0
@ Lol4t0 srand(time(0))rand(70)給出0-69的數字,我不想用0 ... – user3127589
@ user3127589以及__ADD 1__生成的數字。這就是Lol4t0的建議。再次閱讀評論。 –