random number usage in filling 2d array

1.2k Views Asked by At

Below is a small program which has 2-3 Math concepts involved

we have 2d array of $i$ width and $j$ height, idea of this program is to fill

private int[][] ocean = new int[j][i];

$50%$ of 2d array cells with fish (say integer $1$)

public final static int FISH = 1;

And

$~15%$ of 2d array cells with shark (say integer $2$)

public final static int SHARK = 2;

Please help me understand these math concepts(numbered as line #'s), which are actually helping to fill the above conditions.

/**
Visit each cell (in a roundabout order); randomly place a fish, 
* shark, or nothing in each.
*/

Random random = new Random(0); // Create a "Random" object with seed 0
int x = 0;
int y = 0;
for (int xx = 0; xx < i; xx++) {
     x = (x + 78887) % i; // line #5, no idea why 78887(prime number ) is picked This will visit every x-coordinate once
  if ((x & 8) == 0) {   // line #6 
    for (int yy = 0; yy < j; yy++) {
      y = (y + 78887) % j; // line #8 This will visit every y-coordinate once
      if ((y & 8) == 0) { // line #9 
        int r = random.nextInt(); // Line #10 Between -2147483648 and 2147483647
        if (r < 0) { // Line #11 50% of cells start with fish
          sea.addFish(x, y);
        } else if (r > 1500000000) { // Line #13 ~15% of cells start with sharks  
          sea.addShark(x, y);
        }
      }
    }
  }
}
1

There are 1 best solutions below

3
On
x = (x + 78887) % i

This (and its y/j equivalent) look to me like examples of simple linear congruential generators, a basic way to generate pseudo random numbers. I'm assuming the 78887 is somehow related to the dimensions of your ocean.

random.nextInt()

Looks like it just returns a random integer (uniformly distributed with respect to its previously generated numbers) in the range in your comments

if (r < 0)

Since the range you specified (i.e. -2147483648 to 2147483647) has 50% positive numbers and 50% negative, making fish only when negative should happen ~50% of the time.

else if (r > 1500000000)

(21.5-15) / (21.5*2) is actually ~.15 so this creates sharks 15% of the time. In otherwords random.nextInt() will generate a number larger than 1500000000 15% of the time because it is capable of generating $2147483647-1500000000$ numbers larger than $1500000000$ out of a total of $2147483647-(-2147483648)$ numbers in total.