Select a random value from an array

I have an array of numbers, and I want to randomly select a value from this array, and then insert it into an int variable.

I'm not sure which code you will need to see. So,

Here is the for loop that I use to generate 13 numbers (1-13) and insert them into an array.

  int clubsArray []; clubsArray = new int [13]; for(int i = 0; i < clubsArray.length; i++) { clubsArray[i] = i +1; } 

This works well, but now I need to select, for example, 2 random values ​​from this array (and then insert it into a variable that will be used later.

I went through many websites and I saw things like ArrayList<String> to insert values ​​into an array, and then use Random generator = new Random() to select the value from the array, and then .remove() to delete it from an array. But when I used this, it does not work.

+7
source share
1 answer

Just clubsArray[new Random().nextInt(clubsArray.length)] will work

Or, to randomize the order of the elements, use List<?> clubsList=Arrays.asList(clubsArray); Collections.shuffle(clubsList); List<?> clubsList=Arrays.asList(clubsArray); Collections.shuffle(clubsList); .

+24
source

All Articles