0

I am trying to write a guessing game program where a 4 digit number is randomly generated. The numbers need to be unique (as in they do not repeat at any time) I am fairly new to Java and I am having trouble displaying the numbers in an array. Also I can't figure out a way to check a number against the others more than once. EX: If random number A is the same as random number B it will make a new random number A. But I dont know how to check if the NEW random A is the same as number B without writing the same code over and over and over. (clearly some kind of loop but I have no idea which kind)

    import java.util.Random;

    public class Game {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    int rand1 = 0;
    int rand2 = 0;
    int rand3 = 0;
    int rand4 = 0;
    int[] randArray = new int[]{rand1, rand2, rand3, rand4};

    Random randy = new Random();
    int a = randy.nextInt(9);
    int b = randy.nextInt(9);
    int c = randy.nextInt(9);
    int d = randy.nextInt(9);

    //how to check the variable more than one time?
    a = rand1;
    if (b == a) {
        b = randy.nextInt(9);
        }
        else rand2 = b;

    if (c == a || c == b) {
        c = randy.nextInt(9);
        }
        else rand3 = c;

    if (d == a || d == b || d == c) {
        d = randy.nextInt(9);
    }
    else rand4 = d;
    System.out.print(randArray); //prints gibberish
            //prints the numbers fine
    //System.out.print(rand1);
            //System.out.print(rand2);
    //System.out.print(rand3);
    //System.out.print(rand4);
    }

}
John Lapinski
  • 53
  • 1
  • 3
  • 8
  • _"//prints gibberish"_ Use `System.out.print(Arrays.toString(randArray));` – Alexis C. Jan 17 '14 at 19:53
  • @John Lapinski: You need to clarify whether you want unique random numbers or unique digits in the random number. – blackcompe Jan 17 '14 at 20:16
  • @ZouZou Thank you! that easily solve my first problem! Also, Backcompe I wanted unique digits in the random number. Broke it up into digits because I thought it would be easiest to deal with like that but it doesn't necessarily have to be that way – John Lapinski Jan 18 '14 at 16:25

5 Answers5

0

You might first add the random numbers to a java.util.HashSet and then convert it to an array. This way you get rid of all duplicates.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
0

How about using an ArrayList instead?

The syntax is different, but then you can do your program in a looping fashion.

For example:

ArrayList<Integer> randNums = new ArrayList();
while(randNums.size() != 4) {
    int a = randy.nextInt(9);
    if(false == randNums.contains(a))
        randNums.add(a);
}

Edit to add a side note: ArrayList has the prettier printing you are looking for as well.

useSticks
  • 883
  • 7
  • 15
0

For generating random unique integers

Use a Set to create a collection of unique values. Otherwise, for each random number generated, iterate over the array to ensure it's unique before adding it.

Integer[] createGuesses(int numGuesses, int low, int high)
{
    Set<Integer> guesses = new HashSet<>();
    Random rand = new Random();
    while(guesses.size() < numGuesses)
        guesses.add(low + rand.nextInt(high - low));
    return guesses.toArray(new Integer[numGuesses]);
}
blackcompe
  • 3,180
  • 16
  • 27
  • 1
    This will not always add 4 distinct values to the array you return. They might be some `null` elements. – Alexis C. Jan 17 '14 at 20:06
  • @ZouZou: Not if you say `createGuesses(numGuesses, 1000, 9999)`. Null elements? I don't follow. – blackcompe Jan 17 '14 at 20:11
  • 1
    Imagine that you want to generate 3 random numbers (`numGuesses = 3`). Now let's say that the random numbers generated are 5, 2, 5. The last 5 won't be added to your Set. Hence the Set contains only 5 and 2. When you will construct the array to be returned (of length 3), the last element of the array will be fill up with a `null` value. So the resulting array will be `[5,2,null]`. – Alexis C. Jan 17 '14 at 20:18
  • The last line must be: `return guesses.toArray(new Integer[guesses.size()]);` – Meno Hochschild Jan 17 '14 at 20:22
0

If you're OK with storing in memory an 'int' array of 10000 entries:

public class YourClass
{
    private static int final SIZE = 10000;
    private int[]  array = new int[SIZE];
    private int    currIteration = 0;
    private Random random = new Random();

    public YourClass()
    {
        for (int i=0; i<SIZE; i++)
            array[i] = i;
    }

    public int getRandVal()
    {
        int index = random.nextInt(SIZE-currIteration);
        int val = array[index];
        array[index] = array[SIZE-currIteration-1];
        array[SIZE-currIteration-1] = val;
        if (++currIteration == SIZE)
            currIteration = 0;
        return val;
    }
}
barak manos
  • 29,648
  • 10
  • 62
  • 114
0

If you want to change your current array type to Integer instead of an int then i suggest you to take one of the other answers. My first instinct was to show you how clean, readable and simple it will be if you used ArrayList<Integer> and its power and then convert it to Integer[] again no int[].
At the end i decided to wrote you an answer, that may not be the most elegant and defentily not the shortest one, but it will teach you how to think right before you could use tools that will take those element off (ArrayList and its powers as we said).

The algorithm is quite simple.

  1. You create int-array at the n size you needed.
  2. You iterate over it from 0 to n and with every iteration you:
    A. Creating a do-while loop that will generate a random number from 0-9.
    B. Generate a random temp number from 0-9. C. Iterating over your current readArray to look-up if the generated number is inside, and if so it will flag it and stop the look-up process (because we found that we already have it).
    D. Will check if the flag isExists set as true, if so, then will go into step B again otherwise will go to step 3.
  3. If we reached to the end of look-up(for) without changing flag to true, than the temp(generated number) is not at our current array, and it will be safe to add it.
  4. Will check if we reach to the end of the array or there are more array cell to fill. i < readArray.length.

Code:

Random randy = new Random();
int[] readArray = new int[4];
for (int i = 0; i < readArray.length; i++) {
    int temp;
    boolean isExists;
    do {
        isExists = false;
        temp = randy.nextInt(10);

        for (int j = 0; j < i; j++)
        {
            if (readArray[j] == temp)
            {
                isExists = true;
                break;
            }
        }
    } while (isExists);
    readArray[i] = temp;
}

System.out.println(Arrays.toString(readArray));
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36