Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a random value from an Array

I have an Array of number values, and I want to randomly select a value from in that array and then insert it in to an int variable.

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

Here is the for loop that I'm using to generate 13 numbers (1-13) and insert them in to the Array.

    int clubsArray []; 
    clubsArray = new int [13]; 

    for(int i = 0; i < clubsArray.length; i++) { 

        clubsArray[i] = i +1; 

    }

That works fine, but now I need to select for example 2 random values from in that array (and then insert it in to a variable to be used later on.

I've looked around on many websites and I've seen things like ArrayList<String> in order to insert values in to an Array and then use Random generator = new Random() to select the value from the array and then .remove() to remove it from the array. But when ever I have used that it doesn't work.

like image 299
Craig Avatar asked Jan 29 '12 17:01

Craig


People also ask

How do I randomly select a value from an array in PHP?

Method 2: Use array_rand() function to get random value out of an array in PHP. PHP | array_rand() Function: The array_rand() function is an inbuilt function in PHP which is used to fetch a random number of elements from an array. The element is a key and can return one or more than one key.

How do you pick a random number from an array in Python?

Use the numpy. random. choice() function to generate the random choices and samples from a NumPy multidimensional array. Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.


1 Answers

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

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

like image 123
ᅙᄉᅙ Avatar answered Oct 31 '22 19:10

ᅙᄉᅙ