S
S
Sergey Karbivnichy2015-01-31 05:03:17
Java
Sergey Karbivnichy, 2015-01-31 05:03:17

How to generate 4 non-repeating numbers in java?

How to get 4 random numbers in a certain range, so that they don't repeat? I understand that the algorithm is simple, but the pot no longer cooks today, and the solution is needed today. Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
DR_Demons, 2015-01-31
@DR_Demons

Set<Integer> generated = new HashSet<Integer>();
Random r = new Random();
while (generated.size() < 4) {
generated.add(r.nextInt(10) + 1);
}

U
uvelichitel, 2015-01-31
@uvelichitel

I don't own java stdlib, but in general I would generate one from the other

D
de43gy, 2015-07-15
@de43gy

In short, a very crooked code (I wildly apologize), but the meaning is that there is a method with a match check.

public class Main {
    static int arraySize = 4;
    static int maxNumber = 10;
    static int array[];
    public static void main(String[] args) {
        Random random = new Random();
        array = new int[arraySize];
        for (int i = 0; i < arraySize; i++) {
            do {
                array[i]=random.nextInt(maxNumber);
            } while (coincidenceChecking(array[i],i));
        }
    }
    static boolean coincidenceChecking(int num, int numArray) {
        for (int i = 0; i < numArray; i++) {
            if (array[i] == num) return true;
        }
        return false;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question