1

I'm having a hardtime figuring out on how can I generate a twice repeating random number ranges from 1-8 and make it a matrix like this:

5 8 2 5

3 6 4 1

7 6 2 3

4 7 8 1

By the way I plan to make this on android.

Thanks in advance.

Chirag
  • 56,621
  • 29
  • 151
  • 198
KaHeL
  • 4,301
  • 16
  • 54
  • 78

2 Answers2

4

I assume you want a randomized 4x4matrix containing all the numbers 1-8 twice.

You can easily turn a list of 16 numbers into a 4x4matrix. So what you need is a randomized list of the 1-8 numbers.

List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 8; i++) {
  list.add(i);
  list.add(i);
}
// list  = [1,1,2,2,3,3,..,8,8];
Collections.shuffle(list);
// gives something like [1,4,5,2,4,7,..8,1]

To turn this list in a matrix, just read row by row, 4 numbers at a time.

Ishtar
  • 11,542
  • 1
  • 25
  • 31
  • I couldn't believe that something like this would be that simple. My mind was kinda stressed out. Thanks for the help man. You got it. – KaHeL Jul 07 '11 at 10:48
0

What you really want is not random numbers. But a specific set of numbers in a random order!

So start with the required set in ascending order

int[] mySet = Array{1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8}

Then do something like

for (x = 1;99,x++) {
    from = (int)(Math.random()*8);
    to = (int)(Math.random()*8);
    if (from != to) {
       int swap = mySet[to];
       mySet[to] = mySet[from];
       mySet[from] = swap;
    }
}
James Anderson
  • 27,109
  • 7
  • 50
  • 78