如何在随机数组中检查重复项
how to check for duplicates in random array?
我有一个4个数字的数组,在检查重复项时遇到了问题。我的印象是,如果我对arr[I]的数字进行随机化,然后对arr[j]进行随机化,我可以比较它们是否重复,如果为真,我可以再次随机化。如何检查数组的元素是否重复?
int arr[4];
srand(time(0));
for(int i=0; i<4; i++)
{
arr[i] = rand() % 10;
for(int j=i+1; j<4; j++)
{
arr[j] = rand() % 10;
if(arr[j] == arr[i])
{
arr[i] = rand() % 10;
}
}
}
for(int i=0; i<4; i++)
cout << arr[i] << endl;
避免同时使用goto
的另一个技巧是在检查重复项时反转i
for(int j=0; j < i ; j++) if (arr[j] == arr[i]) i--
。
#include <iostream>
#include <ctime>
using namespace std;
int main(void)
{
const int size=100 ;
int arr[100] ;
int i=0;
srand(time(0));
for ( i=0;i<size;i++) {
arr[i]=rand() % size;
for(int j=0; j < i ; j++) if (arr[j] == arr[i]) i--;
}
cout<<" nnn ";
// Loop to display the array arr[ ]
for ( i=0;i<size;i++) cout<<""<<arr[i]<<"t";
cout<<" nPress any key to continuen";
cin.ignore();
cin.get();
return 0;
}
输出:
91 71 14 65 12 25 64 98 83 28
99 9 5 0 89 36 95 55 73 90
78 2 52 70 39 63 17 50 7 58
34 84 40 51 20 31 38 32 35 49
61 66 72 92 6 59 41 13 22 23
81 56 1 16 21 62 57 10 11 54
77 86 76 93 4 96 8 33 94 67
29 48 15 82 97 37 26 46 43 80
68 85 60 30 42 53 18 69 45 88
47 79 75 44 24 27 74 3 19 87
Press any key to continue
它不起作用,因为您正在检查当前索引i上方数组的内容,这些内容甚至还没有写入,您需要检查索引i下方的内容,以找到尚未存储的新值。
代码的第二个问题是,如果已经存在,它只能生成一次新的随机数。程序从不检查第二个备选随机数是否也已经存在。
这应该是正确的:
for (int i=0; i<4; i++)
{
boolean exists = true;
while (exists) {
exists = false;
arr[i] = rand() % 10;
for (int j=0; j<i && !exists; j++)
if (arr[j] == arr[i])
exists = true;
}
}
这里有一个演示程序
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
const size_t N = 4;
int arr[N];
std::srand( std::time( nullptr ) );
for ( size_t i = 0; i < N; i++ )
{
size_t j;
do
{
arr[i] = std::rand() % 10;
j = 0;
while ( j < i && arr[j] != arr[i] ) j++;
} while ( j != i );
}
for ( int x : arr ) std::cout << x << ' ';
std::cout << std::endl;
}
程序输出可能看起来像
5 9 6 7
您可以使用这种方法。当j=i+1直到j<而如果i的值小于j,则该循环没有用处。
for (int i = 0; i<4; i++)
{
arr[i] = rand() % 10;
if (i == 0)
{
continue;
}
for(j=0,j<i-1;j++)
{
if (arr[j] == arr[i])
{
arr[i] = rand() % 10;
}
}
}
相关文章:
- 试图让变量检查数组中的某些内容
- 使用for循环检查数组中的重复项
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 如何检查数组中是否没有值
- 检查数组中的字符对
- 如何检查数组的 3 个元素是否具有相同的值
- 检查彩虹数组(检查数组的反向样式是否与自身匹配)
- 检查数组是否等于的最快方法?
- 如何检查数组是否包含多个元素?
- 检查数组的邻居值
- 检查数组行中每行C++是否始终存在相同的值
- 如果元素的数量已经知道,检查数组或向量中的所有元素是否相等更好?
- 检查数组中的所有对是否都能被 k 整除
- 检查数组中的任何值是否等于添加到数组的当前值
- 如何检查数组中的索引是否为空
- 使用 auto 时不检查数组边界
- 我可以在不循环访问数组/向量的情况下检查数组/向量中的单词吗?
- 如何检查数组中的每个元素是否为素数
- 检查数组中的给定 K 元素
- 检查数组是否'right' (C++)