Question

I am making a basic color guessing game (my firstone) where you get a hex code and you'll get some color alternatives to chose from. However, I've run into some problems. The way I have it set up is that I create some ovals to which I assign random colors (one with the correct one) and that is working all fine.

The problem is that in order for the answer not to be put at the same spot every time I'm trying to randomly generate positions for these ovals, but my code doesn't work. The code (which I thought would reserve spots and assign spots) doesn't reserve spots correctly. I thought it would only go into the else statement if the positions wasn't taken (takenPos[tempRandomNum] == false) but it seems that it always goes into the else statement, even if my print confirms that it generated the same spot multiple times.

Another problem is that if it enters the If statement (which it doesn't right now), generates a new value, and that value is taken it uses the value anyway.

Print: ELSE false 0 ELSE false 540 ELSE false 0 ELSE false 360 ELSE false 360 ELSE false 450 ELSE false 180 ELSE false 360 ELSE false 540

Code:

public int randomOvalPos() {
    //An array of booleans to keep track of if the position is taken.
    boolean[] takenPos = new boolean[difficulty];
    //Temporary variable to return if it gets through the if statement.
    int tempRandomNum = randomNum(0 , difficulty - 1);
    //Check if the position is taken (set before return).
    if(takenPos[tempRandomNum]){
        //If the position is taken I want it to get a new random position.
        //The problem is that if this spot is taken as 
        //well I can't just keep redoing it.
        tempRandomNum = randomNum(0, difficulty - 1);
        takenPos[tempRandomNum] = true;
        return tempRandomNum * 90;
    }else{
        //If it isn't taken set the boolean to true and return the value.
        takenPos[tempRandomNum] = true;
        return tempRandomNum * 90;
    }
}
Was it helpful?

Solution

What I would do (before displaying the ovals to the user) is use the code that currently works and places the answer in the same spot every time, and then shuffle the array using a Fischer-Yates shuffle

Read this question for an implementation on how to do that: Random shuffling of an array

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top