snippetcppModerate
Generate random binary arrays
Viewed 0 times
randomgeneratearraysbinary
Problem
I am fairly new to C++ programming and I, so far, love it. I just have been trying to make sure what I am doing is fast, unique, readable, and efficient. Is there anyway I can improve this code, or is there ways I can improve my coding convention (in C++)? Here I wrote a program that generates a 20 random vectors of binary digits (20 to test "randomness").
#include
#include
#include
#include
void returnarray(bool* array, int size)
{
for (int i = 0; i < size; i++)
{
std::cout << array[i];
}
std::cout << "\n";
}
bool* assignzero(int size)
{
bool* b = new bool[size];
for (int i = 0; i < size; i++)
{
b[i] = false;
}
return b;
}
void generate()
{
int p = 9;
int t = rand() % p;
bool* b = assignzero(p);
for (int x = 0; x < t; x++)
{
b[rand() % p] = true;
}
returnarray(b, p);
}
int main()
{
long inc;
srand(time(0));
while (inc < 20)
{
generate();
inc += 1;
}
}Solution
Initialise your variables
You aren't initialising
Cleanup after yourself
As I mentioned in the comments, you're also leaking memory:
the allocated array is never cleaned up by your application. You should have a paired delete somewhere in the code when you're done with the array:
Expressive names
Think about using more expressive names. You're referring to the array of bools as both 'b' and 'array' in different parts of your code. One of the names tells your there's going to be more than one, whilst the other name hints at the type.
Your
You aren't initialising
inc. This is probably working for you, because the compiler is setting it to 0. This isn't guaranteed though, so you should be explicitly initialising it before you use it:long inc = 0;
srand(time(0));
while (inc < 20)Cleanup after yourself
As I mentioned in the comments, you're also leaking memory:
bool* b = new bool[size];the allocated array is never cleaned up by your application. You should have a paired delete somewhere in the code when you're done with the array:
delete [] b;Expressive names
Think about using more expressive names. You're referring to the array of bools as both 'b' and 'array' in different parts of your code. One of the names tells your there's going to be more than one, whilst the other name hints at the type.
Your
returnarray method actually prints it to the console. If you get the names right, your program will be a lot easier to follow.Code Snippets
long inc = 0;
srand(time(0));
while (inc < 20)bool* b = new bool[size];delete [] b;Context
StackExchange Code Review Q#134664, answer score: 11
Revisions (0)
No revisions yet.