problem with Random()

• March 23rd, 2012, 03:10 PM
Isaksson
problem with Random()
Hello.

Iam having a problem with my code that makes the Random() part.

This is a code for a memory-game in android, but this question is more pure java than android sdk.

This is the code that i run right now.

Code :

```ROW_COUNT = 3 and COL_COUNT = 4 cards = new int [COL_COUNT] [ROW_COUNT];```

Code :

```private void loadCards(){ try{ int size = ROW_COUNT*COL_COUNT;     ArrayList<Integer> list = new ArrayList<Integer>();     for(int i=0;i<size;i++){ list.add(new Integer(i)); }     Random r = new Random();     for(int i=size-1;i>=0;i--){ int t=0;     if(i>0){ t = r.nextInt(i); }     t=list.remove(t).intValue(); cards[i%COL_COUNT][i/COL_COUNT]=t%(size/2); } } catch (Exception e) { Log.e("loadCards()", e+""); }     }```

The problem is that this will always make cards[0][0] = 5 becourse iam not requesting a random
number when i==0

if i try to change that

Code :

``` if(i>0){ t = r.nextInt(i); }```
to
Code :

``` if(i>=0){ t = r.nextInt(i); }```

This is wrong of course: r.nextInt(0) will throw IllegalArgumentException.

So my question is to you guys if there is a way round this problem of mine?

as you could see, iam new to this so please be gentle :o
• March 23rd, 2012, 03:32 PM
Tjstretch
Re: problem with Random()
Are you trying to make it so that the number is likely to get bigger the further you go?

All you have to do is make t = r.nextInt(i+1), so when i=0 it does r.nextInt(1) [Always 0!]

Are you trying to make each a random number?

Choose a max number and always call it like so: r.nextInt(100) [A psuedorandom number between 0 and 99]

Are you trying to make a set of unique values in a random order?

Look into the Collections.shuffle(List<?> list) method, although it would be a bit more complicated because it is a 2d array, but in effect you shuffle each deck in the array with Collections.shuffle(Arrays.asList(cards[i])) where i is a incrementing counter, then you shuffle Arrays.asList(cards) and bam, you got it.
• March 23rd, 2012, 04:53 PM
Isaksson
Re: problem with Random()
Hello.

Iam trying to make it load the numbers two times like this in the logg: