Theo Pearson-Bray
Theo Pearson-Bray

Reputation: 775

Why would someone use a random int and then modulus, rather than a random boolean to make a pseudorandom decision?

Preface- I'm an A level computer science student, and for the most part it's a pretty easy subject. We are graded based on a written test, a programming assignment, and a programming test where we are given pre-written code and asked to modify it.

As homework I was given an old piece of exam code, with the homework being to go through and add comments as to what the code is for.

This is easy to do, as the code is just for a text based noughts and crosses game.

Most of the code isn't too bad (Some of the exam board code is seriously questionable), however the method for choosing which player goes first is a bit strange-

char getWhoStarts() {
        char whoStarts;
        int randomNo;
        Random objRandom = new Random();
        randomNo = objRandom.nextInt(100); 
        if (randomNo % 2 == 0) {
            whoStarts = 'X';
        } else {
            whoStarts = 'O';
        }
        return whoStarts;
}

Obviously, this method works, but I don't really understand why someone would ever generate a random integer, and then check if it is even, when all they want is an evenly weighted random. I could understand if this method had more than two return possibilities, or needed to be weighted, however in this case it makes no sense.

I would replace it with this -

char getWhoStarts() {
    Random r = new Random();
    if(r.nextBoolean()) {
        return  'X';
    } else {
        return  'O';
    }
}

Also, the boolean could probably be a global variable, rather than being initialised each time the method is called.

Could someone explain to me, if there is a reason to do this, what is that reason? And are there any benefits of a random integer rather than a random boolean.

Thanks.

Upvotes: 2

Views: 35

Answers (1)

templatetypedef
templatetypedef

Reputation: 373042

This might be a carryover from C, where the only library function that generates random values (rand) only returns integers. It's actually not a good idea just to look at the remainder modulo two on older implementations, since they famously used to alternate between even and odd numbers. I'd go with the provided function to generate a Boolean value - it's cleaner and less error-prone.

Upvotes: 2

Related Questions