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.
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
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.
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.