Search code examples
javaarraysfor-looprandom

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


Solution

  • 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));
    
    }