-8

I need to generate 8 random numbers: Four being "1"s and the other four being "2"s and then assign them to an array. I already have the code to generate random numbers:

1 + (int)(Math.random() * ((2 - 1) + 1))

What I need to do is to have four "1"s and four "2"s in a random order.

NewBie1234
  • 461
  • 6
  • 23

2 Answers2

2

You don't want random numbers at all. You want 4 1s and 4 2s, in random order. So fill an array with [ 1, 1, 1, 1, 2, 2, 2, 2 ] and shuffle it. Google "Fisher-Yates".

Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
0

I'm not going to give you a full answer because then you wouldn't learn from it. I am going to answer your question by giving an example of a shuffle that you could then use in your situation. This is a custom method to shuffle an array:

public void shuffle(int[] t){
   int temp = 0;
   int j = 0;
   for(int i = 0; i < t.length; i++){
        j = (int)(Math.random() * t.length);
        temp = t[j];
        t[j] = t[i];
        t[i] = temp;
   }
}

Then you can implement this to your array, let's say your array is int[] t = {1,1,1,1,2,2,2,2};. Then you would need to use your method to link both:

shuffle(t);
NewBie1234
  • 461
  • 6
  • 23