C++从随机函数中移除元素

C++ removing elements from random function

本文关键字:元素 函数 随机 C++      更新时间:2023-10-16

我想创建一个2D array a[5][5],其中没有两个相同的数字,并且没有一个元素是0(元素是由函数random(70)生成的),所以我想知道如何删除零并确保没有两个同样的数字?

您可以使用以下

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 

这种方法不需要额外的内存。

另一种方法是使用CCD_ 3。例如

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;
   }
}