How to randomly select from an int array and then delete the selected item

im trying to randomly select from the array to print and then remove it from the array so as not to print the same number twice. I'm a little new to java, so I was wondering if anyone could tell me where I am going wrong.

public static void main(String[] args) {
    int[] colm = { 1, 2, 3, 4, 5, 67, 87 };
    Random rand = new Random();

    for (int i = 0; i < 5; i++)
        System.out.println(" " + colm[rand.nextInt(colm.length)]);

}

thank

+4
source share
3 answers

Random does not give a gurranty of a unique number. you can do the following instead.

public static void main(String[] args) {
    int[] colm = { 1, 2, 3, 4, 5, 67, 87 };
    List l = new ArrayList();
    for(int i: colm)
        l.add(i);

    Collections.shuffle(l);

    for (int i = 0; i < 5; i++)
        System.out.println(l.get(i));

}
+5
source

You are missing the deletion part. Try something like this:

public static void main(String[] args)
{
    Integer [] colm = {1,2,3,4,5,67,87};
    final List<Integer> ints = new ArrayList<Integer>(Arrays.asList(colm));
    Random rand =  new Random();

    for(int i = 0; (i<5) && (ints.size() > 0); i ++) {
        final int randomIndex = rand.nextInt(ints.size());
        System.out.println(" " +  ints.get(randomIndex));
        ints.remove(randomIndex);
    }
}
+3
source

Set Map , , /, () .

0

Source: https://habr.com/ru/post/1534996/


All Articles