-1

So i'm making a small project for school and im trying to get 3 random integers between 1 and 10 and put them in a array, it works but i want to have 3 unique numbers and thats the part wich i can't figure out really.

This is my code so far:

public static void main(String[] args) {
    int[] randomGetal = genereerGetallen();
    for (int i = 0; i < 3; i++) {
        System.out.println(randomGetal[i]);
    }


}

public static int[] genereerGetallen() {
    int[] randomGetal = new int[3];

    for (int i = 0; i < randomGetal.length; i++){
        randomGetal[i] = (int)(Math.random() * 10);
    }

    return randomGetal;
}
Jongware
  • 22,200
  • 8
  • 54
  • 100
SirWiggel
  • 13
  • 3
  • 2
    You could shuffle the numbers from 1 to 10 and take the first three of them. – khelwood Oct 11 '16 at 15:10
  • if you want 3 unique numbers, have you thought about how you would check what values you already have? Considering you generate the 3 random values correctly, how would you check that you already have 1 that exists? What are your thoughts? – Ash Oct 11 '16 at 15:11
  • http://stackoverflow.com/questions/8115722/generating-unique-random-numbers-in-java – sam rodrigues Oct 11 '16 at 15:12

1 Answers1

0

Some guidance to get you in the correct direction: right now, you are simply creating three random numbers. There is no code in there to enforce that constraint that you want.

Thus: you simply have to write some code that knows about "already taken" random numbers. So when you create "new" numbers and you draw one you already picked; you simply try again.

In other words: start looping until you find another random number that isn't "taken".

A completely different approach would be: create an array containing the range of numbers you are interested in; then shuffle that array to then pick the first n (3 right now) entries afterwards.

GhostCat
  • 137,827
  • 25
  • 176
  • 248