Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how select randomly from an int array, then remove the selected element

im trying to select randomly from an array to print it, then remove it from the array, to avoid printing out the same number twice. i am a bit of a java novice so was wondering if someone could point me where im 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)]);

}

thanks

like image 216
user2980885 Avatar asked Feb 13 '23 07:02

user2980885


1 Answers

Random doesn't give gurranty of unique number. you can do 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));

}
like image 132
stinepike Avatar answered Apr 30 '23 06:04

stinepike