Home > Back-end >  Random Number Generator without Repetition c
Random Number Generator without Repetition c

Time:05-29

I'm trying to produce random numbers between 1-10 without any repetition but it's not working. Is there any way to do this without using arrays?

#include<iomanip> 
#include<cstdlib> 
#include<ctime>
#include<time.h>

using namespace std;

int main()
{
    
    srand(time(0));
    int randomNumber=0; 
    
    
   for (int i=0; i<10;i  )
      { 
      randomNumber=(rand() % 10)   1;
      
      cout<<randomNumber<<endl;
     } 
}

CodePudding user response:

You can ensure every random number is unique by permutating an array of 1 to 10 like this:

#include<iomanip> 
#include<cstdlib> 
#include<ctime>
#include<time.h>

#include <ranges>
#include <algorithm>
#include <iostream>

int main()
{
    srand(time(0));

    auto t = std::ranges::iota_view{1, 10};
    std::array<int, 10> nums;
    std::copy(t.begin(), t.end(), nums.begin());
    
    for (int i=0; i < 10 - 1; i  )
    { 
        int randomNumber = rand() % (10 - i);
        if (randomNumber > 0)
            std::swap(nums[i], nums[i   randomNumber]);
        std::cout << nums[i] << std::endl;
    }
}

CodePudding user response:

You can use an unordered map to ensure that the random number generated is unique:

#include<bits/stdc  .h>
using namespace std;

int main()
{

srand(time(0));
int randomNumber=0; 
unordered_map<int,bool> m;
while(m.size()<10)
{
randomNumber=rand() 1;
if(m.count(randomNumber)>0)
  continue;
m[randomNumber]=true;
cout<<randomNumber<<endl;
}
return 0;
}
  •  Tags:  
  • c
  • Related