HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

Generating 1000 random numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomgenerating1000numbers

Problem

I have got the following C code and I feel it is crazy stupid and there must be a better way to do this, but just can't think of one and have yet to learn algorithms.

/*generates 1000 random numbers, lists frequency*/
#include 
#include 
#include 

int main(void)
{
    int count, generated_num ;
    char nums[10] = {0};
    srand(time(NULL));
    for (count = 0; count < 1000; count++) {
        generated_num = rand() % 10 + 1;
        nums[generated_num-1] += 1;
    }

    for (count = 0; count < 10; count++) {
        printf("%d occured %d times\n", count+1, nums[count]);
    }

    return 0;
}


How do I learn to write code that is both efficient in speed but also efficient in the sense it is readable/modifiable/not-a-mess?

Solution

Speed and efficiency

Just don't worry about it. You need to generate 1000 random numbers, and do a little bit of accounting work. Any reasonable solution, such as yours, will perform similarly.

Types

Why use an array of char to keep track of the number of occurrences? You're putting 1000 random numbers into 10 bins. What if one of those bins gets more than 127 items? You would get an overflow.

In summary, those bins should be of type int. Don't even think about skimping on a few bytes of storage, if you want your code to be not-a-mess.

Naming

nums actually stores counts. count, as you've used it in the second loop, actually refers to the generated numbers. I suggest the following renaming:

  • numsbins



  • counti

Context

StackExchange Code Review Q#59141, answer score: 19

Revisions (0)

No revisions yet.