dzroro
dzroro

Reputation: 31

Random numbers in array where the mean is a whole number

I'm working on a a game where I have to generate an int array of 4 elements randomly. My problem is that the mean of all the array elements always have to be a whole number.

Example : array 1 {4 , 2 , 3, 7} , the mean of the array is 28,75 which is not what I'm looking for,

array 2 {3 , 7 , 6 , 4} , the mean is 20 which is good

Now I could make a loop where I check if the mean of the randomly generated numbers is a whole number but that doesn't seems like an efficient way to do that.

The game I'm working for is mean sum for those who know it.

Upvotes: 1

Views: 150

Answers (3)

pjs
pjs

Reputation: 19855

I believe the following function does what you want, given arguments of how many values you want to generate (n) and what's an upper limit for the sum of the values (max).

private static Random r = new Random();

public static int[] makeSet(int n, int max) {
   // The next line guarantees the result is divisible by n
   int currentMax = n * (1 + r.nextInt(max / n));
   Set<Integer> s = new HashSet<Integer>();

   // Generate a set of unique values between 0 and the currentMax,
   // containing those bounds
   s.add(0);
   s.add(currentMax);
   do {
      s.add(r.nextInt(currentMax));
   } while(s.size() <= n);
   Integer[] values = new Integer[n + 1];

   /*
    *  Convert to array, sort the results, and find successive
    *  differences.  By construction, those differences WILL sum
    *  to the currentMax, which IS divisible by the number of
    * values generated by differencing!
    */

   s.toArray(values);
   Arrays.sort(values);
   int[] results = new int[n];
   for(int i = 0; i < n; ++i) {
      results[i] = values[i+1] - values[i];
   }
   return results;
}

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140318

If the mean is a whole number, then the sum must be divisible by 4.

int[] n = new int[4];

Pick four numbers, and calculate their sum:

int sum = 0;
for (int i = 0; i < 4; ++i) {
  sum += (n[i] = random.nextInt());
}

Calculate the remainder of sum / 4:

int r = sum % 4;

So you now need to adjust the sum so that sum % 4 == 0. You can either:

  • subtract r from any of the elements of the array:

    n[random.nextInt(4)] -= r;
    
  • or add 4 - r to any element:

    n[random.nextInt(4)] += 4 - r;
    

Ideone demo

Upvotes: 2

OpenSauce
OpenSauce

Reputation: 8623

Pick a target mean m and random integers n1, n2.

Your array is [m-n1, m+n1, m-n2, m+n2]. Haven't thought about what the properties of this distribution would be, but it should work.

Upvotes: 0

Related Questions