7

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.

Ishtar
  • 11,542
  • 1
  • 25
  • 31
Craig
  • 85
  • 1
  • 2
  • 7
  • you don't really "insert" into an int variable, rather "assign" to :) – Savino Sguera Jan 29 '12 at 17:54
  • possible duplicate of [How to generate a random number with Java from given list of numbers](http://stackoverflow.com/questions/1247915/how-to-generate-a-random-number-with-java-from-given-list-of-numbers) – mmmmmm May 08 '12 at 14:19

1 Answers1

24

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);.

P Varga
  • 19,174
  • 12
  • 70
  • 108
  • Thank you. If I were to use this, should I then remove it from the Array also? (to prevent duplicates being chosen at a later stage) – Craig Jan 29 '12 at 17:55
  • @Craig: Removing an element in an array is O(n), so maybe that is not what you want to do. Maybe you want to shuffle the entire array first? (as one would shuffe a deck of cards) [This](http://stackoverflow.com/a/6127606/165544) is how to do it in C – danr Jan 29 '12 at 18:11
  • Well, probably, or instead check if the output array already has it, and if yes, chose an other one. – P Varga Jan 29 '12 at 19:50