Justin Mulder
Justin Mulder

Reputation: 45

Why does my Random Number Generator not print any 1's?

I made this randomNumberGenerator for a project of mine. It prints all numbers between 1 and 9 randomly, but not the number 1. The if-statements are there to get rid of any consecutive numbers (123 or 555 f.e.). What can I do to make sure it also is able to print 1's. All help is welcome!

The fp part which handles my file should not be relevant to the issue.

Edit: I work in Windows

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main() {
    int n = 3000;
    int randomNumber;
    int lastNumber;

    FILE * fp;
    fp = fopen ("C:\\Users\\furtherDirectoryToFile", "w");

    srand(time(0));

    for (int i = 0; i < n; i++) {
        lastNumber = randomNumber;
        randomNumber = rand() % 10;
        if (randomNumber == lastNumber) {
            continue;
        } else {
            if (randomNumber == ((lastNumber + 1) || randomNumber == (lastNumber - 1))) {
                continue;
            }
        }
        printf("%d\n", randomNumber);
        fprintf (fp, "%d\n", randomNumber);
    }

    fclose (fp);
    return 0;
}

Upvotes: 3

Views: 119

Answers (1)

Ctx
Ctx

Reputation: 18420

The problem is, that your parentheses are set wrong in the if-clause. You need:

if ((randomNumber == (lastNumber + 1)) || (randomNumber == (lastNumber - 1)))

instead you have

(randomNumber == 
       ( (lastNumber + 1) || randomNumber == (lastNumber - 1)))

which evaluates to

(randomNumber == 1)

This is why you never observe a 1.

Further comments:

It, in general, does not make your random numbers more secure if you try to inhibit sequences; on the contrary, if someone knows this algorithm, he can make assumptions on the next digit, which he couldn't make otherwise.

From comments:

As moooeeeep commented, you should initialize the variable randomNumber before you use it first.

JoachimSauer noticed, that lastNumber should only be set if the number is indeed output, otherwise your algorithm can fail.

And as SteveFriedl commented, if you need the range 1-9 instead of 0-9, then use randomNumber = rand() % 9 + 1;

Upvotes: 9

Related Questions