lundi 23 janvier 2017

Get random numbers without repetition in Java. The one I made is too slow

import java.util.Random;
import java.util.ArrayList;

public class RandomExample {
    private ArrayList<Integer> occurredNum = new ArrayList<Integer>();
    private Random r = new Random();
    private int play = 5, repCounter = 0;
    private boolean stopCheck = false;

    public void Tem() {
        occurredNum.add(play);
    }

    public int getRandomWithoutRepetition() {
        while (!stopCheck) {
            play = r.nextInt(9) + 1;

            for (int e: occurredNum) {
                if (play == e) {
                    repCounter++;
                }
            }
            if (repCounter == 0) {
                stopCheck = true;
                occurredNum.add(play);
            }
        }

        repCounter = 0;
        stopCheck = false;

        return (play);
    }

    public static void main(String[] args) {
        RandomExample t = new RandomExample();
        t.Tem();
        System.out.println(t.getRandomWithoutRepetition());
        System.out.println(t.getRandomWithoutRepetition());
        System.out.println(t.getRandomWithoutRepetition());
        System.out.println(t.getRandomWithoutRepetition());
        System.out.println(t.getRandomWithoutRepetition());
        System.out.println(t.getRandomWithoutRepetition());
        System.out.println(t.getRandomWithoutRepetition());
        System.out.println(t.getRandomWithoutRepetition());
    }
}

It prints a random number of numbers(even though I've asked it to print 8 different numbers between 1-9 without repetition) in the output and then goes into a never ending loop while trying to find the next number to print. Never had all 8 numbers in the output. My method seems to be too slow. Is there a better way to get a random number without repeating the number 5(first value of the arrayList) and whichever comes after.




Aucun commentaire:

Enregistrer un commentaire