Random numbers are fun. Really they are. They are at the heart of gambling for sure but they are also a key part of what is called a Monte Carlo Simulation. These simulations are used for all sorts of scientific, financial, engineering and other simulations. They are an attempt to figure the effects of chance, of random reactions, to a formula/algorithm or plan. As such they are an important tool in many fields. But of course Monte Carlo refers to the famous casino so its association with gambling is pretty much unavoidable. This even though the term originated with a group of nuclear researchers that included the computer pioneer John von Neumann. And as it turns out I have a couple of gambling simulations in mind that I think make interesting projects.
The first was inspired by this slot machine simulator that I found as a result of a Tweet on Twitter.
It’s pretty fancy and clearly some serious research went into it. Just for fun I decided to create a very simple version of a slot machine simulation. I didn’t do much research so it’s not as scientific but it was fun to do. The form is below and you can see that I used textboxes to allow the user to specify the starting amount, how much to bet on each spin and how many spins to do. The payoff rate I hard coded in but could easily be another variable the user could set. The payoffs is determined by an other random number and could be a lot more fancy. Probably should be.
1: private void button1_Click(object sender, EventArgs e)
3: int bankRoll = Int16.Parse( this.textBox1.Text);
4: int bet = Int16.Parse(this.textBox2.Text);
5: int cnt = Int16.Parse(this.textBox3.Text);
6: Random r = new Random();
7: for (int i = 0; i < cnt && bankRoll >= bet; i++)
9: if (r.Next(100) > 90)
11: bankRoll += r.Next(100);
14: bankRoll -= bet;
16: this.label1.Text = bankRoll.ToString();
Making this better is an exercise for the student. I hope to write this up in some more detail at a future date but I’m on vacation so it will wait. But there are a couple of things I do like about it. One is that I get to use a more complex terminating clause than we often see in an early student project. It allows for some discussion about the roll of negative numbers in loops. Do you allow them? It depends on the application doesn’t it? Slot machines typically do not grant credit. And of course there are those random numbers to look at so you can get into all sorts of discussions about random numbers, statistics and streaks. Why do you sometimes win? Good stuff.