![]() |
![]() |
|
In class, we wrote a function to compute how many rolls it takes for 2d6 to roll a given target-number.
math: You can say that we'resamplingrollsTilGet 1000 times (or however many times). And, math people would say thatrollsTilGet(3) is arandom variable— not the same sort ofvariablewe mean in programming.
To observe: Each time, as we double the number of samples we take, how quickly do the results seems to converge? Do they converge more quickly fordifficulttargets like 2, or for targetseasytargets like 7?
Generalize these functions to take additional parameters,
so they can use
any number-of-faces of the die,
and also how many copies of the die to roll.
(For example,
We can do this via overloading
:
Java pro tip: You now have two functions, both namedrollsTilGet . But Java can tell which one you are calling, by whether you are passing it three things, or just one. We say we haveoverloadedrollsTilGet . If we are talking/writing about them, we can distinguish their names by providing their full signature:vs.rollsTilGet (int) .rollsTilGet (int,int,int)
so Java knows you intend them as constants (and so it won't let you re-assign them after you initialize them). Also usefinal
, because … well, just because.static
Now, go and change all the 2 and 6's in the following places:
The default values used when
unknown territory: Although these two named-constants look just like local-variables, they're not. They arefields , and are shared by all methods(functions) inside the class (acting like global-variables, in this case). (And moreover, they're static-fields, which means they are shared by all objects. But we haven't made any objects yet, so ignore that.)
Official Misgiving: As an instructor, I like how random-numbers can make for fun loops, and how we can reason a bit about random variables. But, we can't do any unit-tests on them! That is unfortunate that I seem to not be emphasizing that, because it's a critical skill for programming at all levels.
This page licensed CC-BY 4.0 Ian Barland Page last generated | Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |