1

I want to setVisible(false) elements in an array randomly. But when write this code

int random = (int) (Math.random() * 24 + 1);

myLabel.get(random).setVisible(false);

sometimes labels are always visible. Because random gives same number. I do not mean how to generate number without duplicated. Because even the numbers are not duplicated, random may chooses same number twice or more.For example;

Let's say i generate 1 to 5 ints without duplicate like {2,4,5,1,3}. When i try to choose randomly, the program may choose 4 twice and maybe its never choose 3 for 5 choices.

I hope i can write it properly and clear.

fedup
  • 1,209
  • 11
  • 26
M. Aktas
  • 131
  • 1
  • 3
  • 14
  • http://stackoverflow.com/a/30856635/1401019 – Sundararaj Govindasamy Apr 03 '17 at 19:42
  • It is not clear to me, what you mean. When you have a list containing the numbers from 1 to 5 in random order, then all you need is to take one after another. Why the extra step to choose a number randomly out of this list? – vanje Apr 03 '17 at 20:00
  • well i get now. thanks for helping :) – M. Aktas Apr 03 '17 at 20:08
  • On the one hand, I agree that this is a duplicate, and I could dupehammer it, but ... the answers to the linked questions (and there are *many* of them) are somewhat... meh.. I'd rather answer there before closing here... – Marco13 Oct 02 '19 at 21:48

1 Answers1

0

Rather than use an array you could use a List. Generate the random number based on the size of the list. And remove each one as it is used. This is a simple test case showing what I mean.

    List<Integer> myList = new ArrayList<>(Arrays.asList(new Integer[]{1, 2, 3, 4, 5}));
    for (int x = 0; x < 5; ++x) {
        int random = (int) (Math.random() * myList.size());
        Integer myInt = myList.remove(random);
        System.out.println(myInt);
    }
fedup
  • 1,209
  • 11
  • 26