A
A
Anton Mikhailov2014-12-12 20:16:41
linux
Anton Mikhailov, 2014-12-12 20:16:41

How to generate a sequence of numbers without repeats in C++?

Hello.
It is necessary to generate a 2-dimensional array of 0 and 1. I use the standard random (rand, srand). I want to calculate how many zeros and ones will fall out of 100 generations of the array, and how many repetitions of similar combinations will be. I run the program, one-to-one copies are generated without differences.
C++, Linux.

#include <iostream>
#include <cstdlib>
#include <ctime>

#define m_size 3

using namespace std;

void randM()
{
 	srand((unsigned int)time(0));

 	int mas[m_size][m_size];

 	int countZ = 0;
 	int countO = 0;

 	for (int i = 0; i < m_size; i++)
 	{
 		for (int j = 0; j < m_size; j++)
 		{
 			mas[i][j] = rand() % 2;
 			if (mas[i][j] == 0)
 				countZ++;
 			else
 				countO++;
 		}
 	}

 	for (int i = 0; i < m_size; i++)
 	{
 		for (int j = 0; j < m_size; j++)
 		{
 			cout << mas[i][j];
 		}
 		cout << endl;
 	}	

 	cout << "countZ: " << countZ << endl;
 	cout << "countO: " << countO << endl;
}


int main()
{
    //system("clear");
    setlocale(LC_ALL, "Russian");

    int repeat = 0;

    while(repeat < 3)
    {
    	randM();
    	repeat++;
    	cout << endl;
    }

  return 0;
}

There was an idea to throw out numbers from 0 to 9 and translate them into binary code, replacing and supplementing 0 and 1.
It has not yet been possible to fasten urandom. Please help me figure it out.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kstyle, 2014-12-12
@kstyle

take it out of the srand function and paste it into main

A
Armenian Radio, 2014-12-12
@gbg

This option is suitable if a crypto-resistant RNG is not required.
Use bitset:

#include <iostream>
#include <bitset>
#include <stdlib.h>
using namespace std;
int main()
{
    const auto slen=8*sizeof(rand());
    bitset<slen> a(rand());
    for(auto i=0;i<slen;i++)
    {
       cout << a[i] << ' ';
    }
}

D
Don Kaban, 2014-12-12
@donkaban

Worth reading here - www.cplusplus.com/reference/random
And stop "using standard random". Well, the seed must be set outside the function, of course. Getting a random sequence of zeros and ones is easier, probably in a bitset than in an array
. If it's simpler, then:

#include <random>
template <typename T>
T random()
{
   static std::mt19937 rng;
   std::uniform_int_distribution<T>
       dist(std::numeric_limits<T>::min(),std::numeric_limits<T>::max());
   return dist(rng);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question