Custom Distribution of Random Number

Hello all, I am currently in the introduction chapter of the nature of code. I am making a program that generates a random number by comparing two random numbers. I am able to make sense of everything besides what randomCount[x] is generating as i have not set any of the arrays index values to anything.

Any help explaining how this is working would be appreciated. Thank you.

1 Like

Evening Tyler, welcome to the forum. For future post I recommend using the preformatted text button (the one shaped like </>) for sharing code. Makes it a bit easier for us to copy-paste and play around with it :slight_smile:

If I understand your code correctly, int index is the array number (0 - 19), and countArray[x] counts how often that index has been randomly ‘rolled’. You start out with a completely empty array with 20 slots, but each time your sketch goes through draw it adds +1 to one of these 20 slots. How often each slot is rolled is visually shown through graphs because of this line:

rect(x * w, height - randomCount[x], w - 1, randomCount[x]);

it picks the bottom of the screen (height) and subtracts the amount of times that array slot is rolled (-randomCount[x]). The utmost left slot for instance, which is randomCount[0], will often remain 0 for a longer time than the other slots.

Does that clear things up for you?


Thank you, i was trying to figure out how to use the reformatted button.

Ok this is starting to make sense, through changing the size of the array i did realize that the rectangles were visualizing the array length.

One more thing that i could use a little more clarifying on, The line:
int index = int (acceptreject() * randomCount.length); randomCount[index]++;

is taking the generated number from

float acceptreject(){
  boolean foundone = false;
  while (!foundone){
    float r1 = (float) random(1);
    float r2 = (float) random(1);
    if (r2 < r1){
      foundone = true;
      return r1;
  return 0;

which will generate a number between 0-19 and that is where the ‘rolling’ comes from, and in turn makes one of the rectangles increase in height?

The while loop within float acceptreject() keeps rolling/randomising r1 and r2 until r1 is bigger. This value will be returned and multiplied by randomCount.length (which is in this case 20). After the multiplication the number will be rounded to a whole number because it’s between int( … ).

This rounded number will be used to pick the right slot for randomCount[index]. So if the calculations of index results in 15, it means that array slot #15 gets selected. By adding ++ right after it it means that the value within that slot increases by one.

Since the returned value will be between 0 and 1 (you can test this by adding println(r1) right after foundone = true;) and gets multiplied by the length of the array, the outcome of index won’t exceed the slot numbers of your array.