João Alves Coelho João Alves Coelho - 4 months ago 8
Java Question

How to get 7 random numbers from lists

I have the following code:

public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(10);
list1.add(8);
list1.add(5);
list1.add(3);
list1.add(9);
list1.add(2);

Random e = new Random();

ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(50);
list2.add(18);
list2.add(44);
list2.add(4);
list2.add(23);
list2.add(37);
list2.add(38);
list2.add(26);
list2.add(25);
list2.add(10);
list2.add(30);
list2.add(49);
list2.add(14);
list2.add(29);
list2.add(42);
list2.add(5);
list2.add(11);
list2.add(21);
list2.add(79);
list2.add(15);
list2.add(17);
list2.add(24);
list2.add(1);
list2.add(13);
list2.add(45);
list2.add(6);
list2.add(27);

Random n = new Random();

System.out.println(list1.get(n.nextInt(list1.size() - 1)));
System.out.println(list2.get(n.nextInt(list.size() - 1)));

}


How do I get 2 random numbers (no duplicate) from list1 and 5 random numbers (no duplicate) from list2 at the same time without having to run the code 7 times to get the 7 numbers I need

Answer

Whenever you get a random value from the list, remove that element.

If you need to, create a copy of the list to preserve the original data


public int[] getRandomData(ArrayList<Integer> list, int count) {
    int[] result = new int[count];
    while (count > 0 && list.size() > 0) {
         int index = (int) (Math.random() * list.size());
         result[count - 1] = list.get(index);
         list.remove(index);
         count--;
    }
    return result;
}

called by:

int[] stuffFromList1 = getRandomData(list1, 2);
int[] stuffFromList2 = getRandomData(list2, 5);