-1

I'm trying to write a method that gets a list of numbers from 1 to 10 where there will be no duplicates. Also the member must not be zero. However, after many attempts I failed to solve the problem, this is my code:

public ArrayList<Integer> dobijNiz() {
        int min = 1;
        int max = 10;
        ArrayList<Integer> lista = new ArrayList<Integer>();
        Random random = new Random();

        for (int i = 0; i < 11; i++) {
            int broj = random.nextInt((max - min) + 1) + min;

            lista.add(broj);   
        }
        System.out.println(lista);
        return lista;
    }

Output:

[2, 3, 3, 3, 4, 6, 10, 8, 2, 7, 9]

I forgot to say that Collections.shuffle doesn't work

Mihailo E
  • 1
  • 4
  • Program to the `List` interface (instead of specifying `ArrayList` everywhere). `List lista = IntStream.range(min, max).boxed().collect(Collectors.toList());` and then `Collections.shuffle(lista, ThreadLocalRandom.current());` – Elliott Frisch Jul 04 '21 at 15:30
  • 1
    There is a problem in the question. If you need 10 random numbers and list size is 10, then it is always has to be numbers between 1 to 10 only. Assuming you are expecting 5 random from 1 to 10, then this is how it would be. You should also need to have a check of max-min is greater than count to ensure it does to go infinite loop :) [![Working Example][1]][1] [1]: https://i.stack.imgur.com/BOLmw.gif – Venkateswara Rao Jul 04 '21 at 15:48

1 Answers1

2

Add all possible numbers into the ArrayList, then use Collections.shuffle to shuffle the list.

int min = 1;
int max = 10;
ArrayList<Integer> lista = new ArrayList<Integer>();
for (int i = min; i <= max; i++) {
    lista.add(i);   
}
Collections.shuffle(lista);
Spectric
  • 30,714
  • 6
  • 20
  • 43