• Jamie (unregistered)

At least half of my runs look like this:

``` 10 > -10
BUSTED```

but I did manage a successful run at last:

``` 10 > -10 +20
20 > -10 -10 +20
20 > -10 -10 +20
20 > -10 +20
30 > -10 +20
40 > -10 +20
50 > -12 +24
62 > -15 +30
77 > -19 +38
96 > -24 +48
120 > -30 -45 +90
135 > -33 +66
168 > -42 +84
210 > -52 +104
262 > -65 -97 +194
294 > -73 +146
367 > -91 +182
458```

The code is some pretty basic ruby to run the simulation.

• Jamie (unregistered) in reply to Jamie
Jamie:
The code is some pretty basic ruby to run the simulation.

And of course, without an account I can't edit my post. I went with an initial bet of 25% of current (or minimum) and a repeated 50% bumpup on loss (rather than only bumping once).

• Jim Cooper (unregistered) in reply to randomlyVarying
randomlyVarying:
Yes, the outcomes of two tosses (turn? role? death spiral?) of the roulette. Yes, the sequence is completely random. That does not mean, however, that all sequences are equally likely to occur.

For an entertaining summary, see: http://www.ted.com/talks/lang/eng/peter_donnelly_shows_how_stats_fool_juries.html

I think you need to watch that again. For sequences of a given length where all outcomes are equally likely (eg for fair coins or dice, but not red/black/zero on roulette wheels), all sequences ARE equally likely. So HTHTHT is as likely as HHHHHH.

That video shows that not all equal length subsequences within a larger sequence are equally likely, which is a different thing altogether, and not relevant to this question.

• Matt (unregistered)

The fact that a table was showing 4 reds in a row does not affect the probability of the next roll being black or red, in the slightest bit!

Each roll of the wheel is independent in probability from the last roll. Black or Red odds will always be a little less than 50% (because of the 2 greens, depending on the wheel)

I always find it amusing at casinos when people are running up and down an aisle of roulette tables looking for streaks of black/red so they can bet the opposite.

• mpbk (unregistered) in reply to Guillaume

The Real WTF is that no one actually posted any real code until the bottom of the first comment page.

• (cs) in reply to CommonSense
CommonSense:
The point of this "practice" clearly isn't to try coding a solution, but being a good enough programmer to analyze the problem first and realize there's no pattern to roulette so no code needs to be written.

The assignment wasn't to code a solution, it was to code a simulator. As a video game programmer in training, I find it to be rather relevant.

• Steve (unregistered)

Used 50/50 odds and any profit was usually correlated to how many tables there were rather than rounds. However as soon as i changed the probability to include the two green spaces i started losing more then winning.

• (cs) in reply to Jim Cooper
Jim Cooper:
I think you need to watch that again. For sequences of a given length where all outcomes are equally likely (eg for fair coins or dice, but not red/black/zero on roulette wheels), all sequences ARE equally likely. So HTHTHT is as likely as HHHHHH.

That video shows that not all equal length subsequences within a larger sequence are equally likely, which is a different thing altogether, and not relevant to this question.

What are the odds of flipping a coin 4 times and getting heads every time? What are the odds of flipping a coin 5 times and getting heads every time?

• Hatterson (unregistered) in reply to Kanazuchi

It depends on your definition of win

If by win you mean increase your bankroll, then you cannot win. The simple reason being that the only way to gaurantee a 'win' is to have an infinite bankroll. If I have an infinite bankroll and I add \$1 to it, I still have an infinite bankroll.

Also, if my bankroll was countably infinite adding a constant leaves it countably infinite. If it was uncountably infinite adding a constant leaves it as such. So I cannot even increase the "size" of my infinity.

However if by win you mean dividing the game into rounds and see that you come out of the round with more than you went in, then you can indeed win. A round would be defined as starting when you place your first bet and ending when you win for the first time. You come out of that with \$bet more than you entered.

The question then becomes how can I make sure I have enough to complete a round and the answer bring us back to the infinity issue.

However, if we have a situation where your bankroll was \$1 and the casino was willing to give you an infinite line of credit with 0 interest then you could come out on top using the system as your first win would allow you to pay off your debt and end with \$2.

In laymans terms, If I have infinite time and money why am I spending it betting on a coin toss to win \$1?

• Philip Skinner (unregistered)

Unfortunately the chance of black or red does not matter on what came before, so there is always a 1 in 2 chance of it being either red or black.

An interesting article in New Scientist discussed this a couple of weeks ago, having 20 blacks in a row has the same probability as having red, black, red, black etc.

• (cs) in reply to Dazed
Dazed:
My first little book on mathematics did a good job of explaining how roulette works, and how roulette strategies don't. It ended with advice along the lines of: rather than play roulette, flush your money down the toilet; it's equally effective and saves the hassle of getting to the casino.

Supposedly, Albert Einstein once commented that the only way to make money playing roulette is to steal it off the table when the croupier isn't looking.

Jim Cooper:
As we all know, what the wheel span last time is completely irrelevant - although it is truly surprising the number of people who don't actually believe that in their heart of hearts :-)

I don't believe it. If I saw a roulette wheel hit black 99 times in a row, I'd assume that it was rigged and bet against everyone else placing a bet on that spin.

Anyone care to explain the rules for 0 and 00?

• civild (unregistered)

Here's my enterprise-y, bug-ridden PHP code.

http://pastie.org/588581

It seems to lose more often than win, so I won't be trying it at the casino any time soon... (either that or php's rand() isn't the greatest)

• TheCPUWizard (unregistered)

Actually "The Perch" is one way to "conserve" your money. Unless there are a large number of visible tables, one will spend a significant amount of time on the perch - and therefore NOT losing money.....

• CGJ (unregistered)

I'm learning Python so I decided try it with this problem. Instead of trying to meet the specifications, I went for the bonus points (what's the probability of gaining \$400).

This is by no means an efficient piece of code. Like I said I'm still learning:

```import random

def spin():
spin = random.randint(1,38)
if spin % 2 == 0:
color = "red"
else:
color = "black"
if spin == 0: color = "green"
if spin == 19: color = "green"
return(color)

def perch(turns, startingbankroll):
Gain = Bankrupt = 0
for turn in range(turns):
bankroll = startingbankroll

while 400 > bankroll > 0:
red = black = green = 0
for i in range(4):
color = spin()
if color == "red": red += 1
if color == "black": black += 1
if color == "green": green += 1

if red == 4:
bankroll -= 10
color = spin()
if color == "red":
bankroll += 20
else:
bankroll -= 15
color = spin()
if color == "red":
bankroll += 30

if black == 4:
bankroll -= 10
color = spin()
if color == "black":
bankroll += 20
else:
bankroll -= 15
color = spin()
if color == "black":
bankroll += 30

if bankroll >= 400:
Gain += 1
else:
Bankrupt += 1

print("Starting with \$" + str(startingbankroll) + " and spinning " + str(turns) + " times:")
print("Ended with \$400 " + str(Gain) + " times and went bankrupt " + str(Bankrupt) + " times.")
print("Making a " + str(Gain * 100 / turns) + "% success rate.")
```

Output:

```>>> perch(100000, 10)
Starting with \$10 and spinning 100000 times:
Ended with \$400 1906 times and went bankrupt 98094 times.
Making a 1% success rate.
```
• quintopia (unregistered)

Yeah, this one is a lot easier than the last one, especially since all of the rules can be boiled down to:

Pick a random number in [0,1]

-Win \$10 if it's <2*(9/19)^6 -Else, Win \$20 if it's <2*(9/19)^6+2*(9/19)^6*(10/19) -Else, Lose \$25 if it's <2*(9/19)^6+2*(9/19)^6*(10/19)+2*(9/19)^5*(10/19)^2 -Otherwise, no change*

The number of tables is only relevant to determining how long it takes to go out (and the assumption that you can only bet on one table at a time makes this dependence tricky) and the actual record of red/blacks is entirely moot.

On the other hand, simulating the physics of an actual roulette wheel could make it much harder and much more interesting.

*I sometimes screw up probability calculations, so I may be missing something here.

• Not always wrong (unregistered) in reply to Roflo
Roflo:
Anyone care to explain the rules for 0 and 00?
If you bet Red or Black and it comes up a Zero, you lose.

IIRC, betting Zero usually pays out at 35:1.

The number of zeros available depends on the house though - casinos can have between one and three zeros which obviously affects the profit margin.

• Not always wrong (unregistered) in reply to Not always wrong

[quote user="Not always wrong"][quote user="Roflo"]AnyoneIIRC, betting Zero usually pays out at 35:1.[/quote]Sorry, that should be 'betting a specific Zero' If you bet on 0 and 00 comes up, you still lose.

• Daniel (unregistered)

Where we go, crappy C++:

```#include <iostream>
using namespace std;

typedef enum { RED, BLACK, GREEN, UNDEF } Color;

class Table
{
private:
int nRuns;
Color lastColor;

public:
Color curColor;
Table ()
{
nRuns = 0;
lastColor = curColor = UNDEF;
}
bool  Got4 (void);
void  Roll (void);
};

bool Table::Got4()
{
return (nRuns >= 4) && (curColor != GREEN);
}

void Table::Roll ()
{
int n = rand() % 38;
if (n < 2)
curColor = GREEN;
else if (n & 1)
curColor = RED;
else
curColor = BLACK;
if (curColor == lastColor)
nRuns++;
else
{
nRuns = 1;
lastColor = curColor;
}
}

int ThePerk (int startAmt, int nTables, int endAmt)
{
int curAmt = startAmt;
Table *table = new Table [nTables];
Color betColor;
int i;

while ((curAmt >= 10) && (curAmt < endAmt))
{
for (i =0; i < nTables; i++)
{
table[i].Roll();
if (table[i].Got4())
break;
}
if (i < nTables)
{
cout << "Moving to table " << i+1 << endl;
curAmt -= 10;
betColor = table[i].curColor == RED ? BLACK : RED;
table[i].Roll();
if (betColor == table[i].curColor)
{
curAmt += 20;
cout << "Won" << endl;
}
else if (curAmt >= 15)
{
cout << "Lost, trying again" << endl;
curAmt -= 15;
table[i].Roll();
if (betColor == table[i].curColor)
{
curAmt += 30;
cout << "Won" << endl;
}
else
cout << "Lost again!" << endl;
}
else
{
cout << "Lost, no money to try again" << endl;
}
cout << "Now I\'ve got \$" << curAmt << endl;
}
}
return curAmt;
}
```
• (cs)

Of course, this is the theoretical part where there is 18/38 chance to win. Don't forget the zeros! In reality, that is only what the chance is supposed to be. The laws of physics says that the chance is likely not exactly that depending on a lot of random factors related to the physical motion. Some guy avenged them for a casino and found an extra lucky wheel.

• Joe (unregistered)

I don't code much any more, but here's the pseudocode for a highly-optimized algorithm:

#define MAX_TURNS = 40 (I'm not going to spend more than 40 times watching the little ball go around

generate all possible ball-landings for the tables (38**MAX_TURNS) * T. Merge each 40-character table sequence (evenly) into a single string (length 40*T).

Replace even numbers with "B" and odd numbers with "R"

Search for strings of R(T-1 other letters)R(T-1 other letters)R(T-1 other letters)R(T-1 other letters)R (this is a win). Replace the first R in that sequence with a +.

Search for strings of R(T-1 other letters)R(T-1 other letters)R(T-1 other letters)R(T-1 other letters)B (this is a loss). Replace the first R in that sequence with a -.

Search for strings of B(T-1 other letters)B(T-1 other letters)B(T-1 other letters)B(T-1 other letters)B Replace the first B with a +.

Search for strings of B(T-1 other letters)B(T-1 other letters)B(T-1 other letters)B(T-1 other letters)R. Replace the first B with a -

Walk through the 38**MAX_TURNS and count +'s, subtracting -'s until you get to either the end of the string (in which case you left with a profit) or a total of 0 (you lost your money) Associate that value with the strings.

Sort the list of 38**MAX_TURNS by the associated won value.

The first one in the resulting list is the most you can possibly win. The number of non-zero items / 38**MAX_TURNS is the probability of winning.

This doesn't do the bet-1.5 if you lose rule, but a simple addition of another pair of regexps would fix that.

--Joe

• Dennis (unregistered) in reply to Matt
Matt:
I always find it amusing at casinos when people are running up and down an aisle of roulette tables looking for streaks of black/red so they can bet the opposite.

Some casinos have displays on each roulette table that show the most recent numbers. Many also distribute pads and pencils so players can do their own recording.

• Frederick (unregistered)

Isn't this the gambler's fallacy? (It might work, but it's fallacious.)

• Dennis (unregistered) in reply to Not always wrong
Not always wrong:
Not always wrong:
AnyoneIIRC, betting Zero usually pays out at 35:1.
Sorry, that should be 'betting a specific Zero' If you bet on 0 and 00 comes up, you still lose.
Yes, and you can bet both zeros together which pays 17 to 1.
• Programming Praxis (unregistered) in reply to CommonSense

The probability of red or black is not 0.5, Vegas tables have one and sometimes two green spaces.

• Aris (unregistered)

I was in a casino in Vegas with some friends some weeks ago, playing roulette (not me, I said I made too much maths for playing roulette). My friend played red when the last 4 (or five) moves were blacks. The roulette's guy told him, the most seriously possible : "don't play against the color".

And of course, he lost all of his money :)

• Anon (unregistered) in reply to thnurg
thnurg:
What the hell does quote-unquote The Law of Large Numbers mean?

Surely that should be quote The Law of Large Numbers unquote.

quote-unquote bothers the crap out of me. The whole point of it is to quote a phrase, but if you simply say quote-unquote before the phrase how do we know when the phrase is finished?

This isn't grammer Nazism, it's logic Nazism.

quote-unquote empty string

• SR (unregistered) in reply to CGJ
CGJ:
```    spin = random.randint(1,38)
```if spin == 0: color = "green"
if spin == 19: color = "green"
```
```

I'm no Python expert wouldn't

`random.randint(1,38)`
never turn up a zero?

• SR (unregistered) in reply to SR
SR:
I'm no Python expert wouldn't

Clearly I'm no English expert today, either. I meant "I'm no Python expert but wouldn't..."

• (cs) in reply to Jim Cooper
Jim Cooper:
randomlyVarying:
Yes, the outcomes of two tosses (turn? role? death spiral?) of the roulette. Yes, the sequence is completely random. That does not mean, however, that all sequences are equally likely to occur.

For an entertaining summary, see: http://www.ted.com/talks/lang/eng/peter_donnelly_shows_how_stats_fool_juries.html

I think you need to watch that again. For sequences of a given length where all outcomes are equally likely (eg for fair coins or dice, but not red/black/zero on roulette wheels), all sequences ARE equally likely. So HTHTHT is as likely as HHHHHH.

That video shows that not all equal length subsequences within a larger sequence are equally likely, which is a different thing altogether, and not relevant to this question.

That's not correct. All equal length subsequences within a larger sequence are equally likely (assuming equal probability for each possible outcome), and Mr. Donnelly didn't say otherwise. What he said is that some subsequences will occur sooner than others on average. Important difference.
• teh jav (unregistered)
```
import java.util.*;
public class RouletteWheel {
private final Random random;
public RouletteWheel(Random random) {
this.random = random;
}

public RouletteWheel() {
this.random = new Random();
for (int i = 0; i<4; i++){
}
}

private Colour getNextSpin() {
int rval = random.nextInt(18 + 18 + 2);
if (rval < 18) return Colour.RED;
rval -= 18;
if (rval < 18) return Colour.BLACK;
return Colour.GREEN;
}

void next() {
history.remove(0);
}
}

enum Colour {
RED, GREEN, BLACK
}

import java.util.*;
public class Play {
public static void main(String argv[]) {
int noOfTables = 4;
int startingCash = 10;
int endingAmount = 400;

int goes = 10000;

simulate(goes, noOfTables, startingCash, endingAmount, new PerchStrategy());
simulate(goes, noOfTables, startingCash, endingAmount, new RedStrategy());

}

static void simulate(int goes, int noOfTables, int startingCash, int endingAmount, Strategy strategy) {
int wins = 0;
int loss = 0;

for(int i = 0; i<goes; i++) {
int cash = doStuff(noOfTables, startingCash, endingAmount, strategy);
if(cash > 0) {
wins++;
} else {
loss++;
}

}
System.out.println("Wins: " + wins + " - " + (((float)wins / goes) * 100));
System.out.println("Loss: " + loss + " - " + (((float)loss / goes) * 100));
}

public static int doStuff(int noOfTables, int cash, int endingAmount, Strategy strategy) {

RouletteWheel[] tables = new RouletteWheel[noOfTables];
for(int i =0;i<noOfTables;i++) {
tables[i] = new RouletteWheel();
}

do {
Bet bet = strategy.beStupid(tables);
for(RouletteWheel table : tables) {
table.next();
}
if (bet != null) {

if( bet.table.history.getLast() == bet.colour) {
cash += bet.amount * 2;
} else {
cash -= bet.amount;
}
}

} while(cash > 0 && cash <= endingAmount);
return cash;
}
}
interface Strategy {
Bet beStupid(RouletteWheel[] tables);
void won();
void lost();
}

class Bet {
int amount;
Colour colour;
RouletteWheel table;
}

class RedStrategy implements Strategy {
public Bet beStupid(RouletteWheel[] tables) {
Bet b = new Bet();
b.amount = 10;
b.colour = Colour.RED;
b.table = tables[0];
return b;
}
public void won() {}
public void lost() {}
}

class PerchStrategy implements Strategy {
boolean lostLastTime = false;
RouletteWheel lastTimeTable = null;
Colour lastTimeColour = null;
public Bet beStupid(RouletteWheel[] tables) {
if (lostLastTime) {
Bet b = new Bet();
b.amount = 15;
b.colour = lastTimeColour;
b.table = lastTimeTable;
return b;
}
RouletteWheel table = getAllOneColour(tables);
if(table == null) return null;
Bet b = new Bet();
b.amount = 10;
b.colour = table.history.getFirst();
b.table = table;
return b;
}
RouletteWheel getAllOneColour(RouletteWheel[] tables) {
for(RouletteWheel table : tables) {
Colour c = table.history.getFirst();
if (c == Colour.GREEN) continue;
for(Colour cur : table.history) {
if(c != cur) continue;
}
return table;
}
return null;
}

public void won() {
lostLastTime = false;
}
public void lost() {
if(lostLastTime) {
lostLastTime = false;
return;
}
lostLastTime = true;
}
}
```
• teh jav (unregistered)

\$ java Play Wins: 3334 - 33.34 Loss: 6666 - 66.659996 Wins: 3332 - 33.32 Loss: 6668 - 66.68

Now assuming I've not messing something up (quite likely) it makes no difference.

• Graham Stewart (unregistered)

Given the number of people offering unrequired lectures on statistics and the Gambler's Fallacy, perhaps the next BYOC problem should be to code up the Boy-Girl Paradox?

Boy Girl Paradox You ask a woman how many children she has and she says two. Then for some strange reason you ask her, "Is at least one a girl?", to which she replies, "Yes".

So what are the odds that she has a girl and a boy?

(to avoid some argument: assume this is a perfect world where the odds of boy or girl conception are 50/50 and that there are no genetic "third sex" possibilities)

Or if that is too easy then possibly go for Monty Hall? :)

• Hatterson (unregistered) in reply to Ilya Ehrenburg
Ilya Ehrenburg:
Jim Cooper:
randomlyVarying:
Yes, the outcomes of two tosses (turn? role? death spiral?) of the roulette. Yes, the sequence is completely random. That does not mean, however, that all sequences are equally likely to occur.

For an entertaining summary, see: http://www.ted.com/talks/lang/eng/peter_donnelly_shows_how_stats_fool_juries.html

I think you need to watch that again. For sequences of a given length where all outcomes are equally likely (eg for fair coins or dice, but not red/black/zero on roulette wheels), all sequences ARE equally likely. So HTHTHT is as likely as HHHHHH.

That video shows that not all equal length subsequences within a larger sequence are equally likely, which is a different thing altogether, and not relevant to this question.

That's not correct. All equal length subsequences within a larger sequence are equally likely (assuming equal probability for each possible outcome), and Mr. Donnelly didn't say otherwise. What he said is that some subsequences will occur sooner than others on average. Important difference.

In an infinite sequence you have certain subsequences which 'clump' together due to repetition but these clumps are further apart.

What this means is that when taking any finite sequence of flips there's a chance that it will fall in the middle of a clump and a chance that it will fall between clumps. You end up with subsequences that will, in laymans terms, happen a lot or happen a little but not usually an average amount. The cases for 'a lot' of an occurrence and 'a little' come up more often than 'average'.

For a sequence like HTH you have the chance to get a run like HTHTHTH and get several in a row.

For HTT you have a 50% chance to 'start' the sequence, then 50% to proceed and 50% to restart, then 50% to win and 50% to restart. Compared to HTH where you have a 50% chance to start, then 50% to proceed and 50% to restart, then 50% to win or 50% to lose.

• teh jav (unregistered) in reply to teh jav
teh jav:
\$ java Play Wins: 3334 - 33.34 Loss: 6666 - 66.659996 Wins: 3332 - 33.32 Loss: 6668 - 66.68

Now assuming I've not messing something up (quite likely) it makes no difference.

Not that is changes the results:

```	RouletteWheel getAllOneColour(RouletteWheel[] tables) {
outer: for(RouletteWheel table : tables) {
Colour c = table.history.getFirst();
if (c == Colour.GREEN) continue;
for(Colour cur : table.history) {
if(c != cur) continue outer;
}

return table;
}
return null;
}
```
• An Onymous (unregistered)

Nothing to do with code, but I read Harry Anderson's "Games You Can't Lose: A Guide for Suckers" when I was younger. Been a while, but I do recall his advice for roulette was to bet with a run of a specific color/number/area of the wheel. His theory was that there may be a "sweet spot" on the wheel that favors that particular location.

He does warn, though, that nobody beats the house. :)

• (cs) in reply to Graham Stewart
Graham Stewart:
Given the number of people offering unrequired lectures on statistics and the Gambler's Fallacy, perhaps the next BYOC problem should be to code up the Boy-Girl Paradox?
Boy Girl Paradox You ask a woman how many children she has and she says two. Then for some strange reason you ask her, "Is at least one a girl?", to which she replies, "Yes".

So what are the odds that she has a girl and a boy?

(to avoid some argument: assume this is a perfect world where the odds of boy or girl conception are 50/50 and that there are no genetic "third sex" possibilities)

Or if that is too easy then possibly go for Monty Hall? :)

Err.. That seems obvious. The odds that she has a boy and girl at the end of the statement is 2/3rds.

Four possibles: BB BG GB GG

The question "Is at least one a girl?" eliminates the first option, leaving three. 2/3 of those are one girl, one boy. Simple.

Note that you also have to assume that the children's genders are independent of each other, which is actually not the case in real-life siblings with the same parents.

• Hatterson (unregistered) in reply to An Onymous

What this is essentially saying is that it is more likely the wheel isn't 100% fair than that a certain sequence appears.

To equate to flipping a coin. Lets assume I don't know if the coin is fair or not (similar to a roulette wheel in a casino, I don't know for sure that it's not imbalanced). If I see someone taking \$1 bets on a coin, H means you win \$3 T means you lose. If I also see them flip 10 T in a row I begin to become skeptical of this coin and think that it's weighted to come up with T more often as the chance of a fair coin hitting 10 Ts (roughly .1%) is less than the chance of someone abusing a weighted coin to take money from people.

• (cs)

The confusing part is that if you look at a sequence of 5 BEFORE you start, there's fairly low odds of them all coming out the same color.

However, if you have a PREVIOUS sequence of a color, the odds are 50/50 (assuming no rigging and only 2 possible outcomes) that the next roll will be the same color.

So the odds of 5 black in a row are different from the odds of the next roll being black (given it-doesn't-matter already happened before).

Of course, it's probably hard to remember that in the gambling place after drinks. :P

And apparently the script thinks I'm a spammer for some reason? Or is that a REAL error this time? No real way to know -- maybe if I remove the word casino?

EDIT: Well -- that did it. Except I realized that I had "the word" again below so who knows how this thing works. TRWTF is TDWTF

• Art Metz (unregistered)
Like my netbook, I never like to leave town without legal representation.

Your netbook doesn't like to leave home without legal representation?

• (cs)

Ugly Python version:

```RED, BLACK, GREEN = range(1, 4)

def get_random_color():
import random
i = random.randint(1, 38)
if i <= 18:
return RED
if i <= 2 * 18:
return BLACK
return GREEN

class Table(object):
def __init__(self):
self.rounds = []
self.rounds.append(get_random_color())
self.rounds.append(get_random_color())
self.rounds.append(get_random_color())
self.rounds.append(get_random_color())
self.bet = None
self.bet_size = 0
def calc_bet_size(self, bankroll):
self.bet_size = max(10, self.bet_size * 1.5)
self.bet_size = min(bankroll, self.bet_size)
return self.bet_size
def try_bet(self, bankroll):
if bankroll <= 0:
self.bet = None
return bankroll
if self.rounds[0] == self.rounds[1] == self.rounds[2] == self.rounds[3]:
if self.rounds[0] == RED:
self.bet = BLACK
return bankroll - self.calc_bet_size(bankroll)
elif self.rounds[0] == BLACK:
self.bet = RED
return bankroll - self.calc_bet_size(bankroll)
self.bet = None
return bankroll
def play_round(self, bankroll):
self.rounds = self.rounds[1:]
self.rounds.append(get_random_color())
if self.bet == self.rounds[-1]:
bankroll += self.bet_size * 2
self.bet_size = 0
return bankroll

def play(bankroll, number_of_tables, rounds=100):
tables = [Table() for i in range(number_of_tables)]
for round in range(rounds):
for t in tables:
bankroll = t.try_bet(bankroll)
bankroll = t.play_round(bankroll)
return bankroll

tries = 1
wins = 0
losses = 0
while True:
#for i in range(100):
x = play(100, 50)
print x
if x > 100: wins += 1
if x < 100: losses += 1
if x >= 400:
print "Probability:", 1.0/tries
break
tries += 1
print 'Wins:', wins
print 'Losses:', losses```

The index of code entries is as allways at http://tinyurl.com/mcxts8 (tinyurl to pass thru spam filter)

• (cs) in reply to There is so much WTF in this I don't know where to start
There is so much WTF in this I don't know where to start:
The roulette table has NO MEMORY of the previous sequence of events (black or red). Read this several times till you understand this concept.

Randomness is not the roulette table keeping a tally of all the reds and blacks in sequence and making sure there are the same number of each (ignoring the greens which I'll get to in a minute) or a fair-looking alternation of red and black sequences.

The sequence of random black and red is truly random - 100 black followed by 100 red is JUST AS LIKELY as RED-BLACK-RED-BLACK (repeated forever) or RRRR-BBBB-RRRR-BBBB...or any other combination.

Each subseqent outcome is completly unaffected by the previous colour.

As far as the odds being 1:1 - the 2 greens are how the house winds. Yes - there are equal number of reds and blacks, so 1:1 payout looks like a good deal. However, there a 2 green possibilites on the table (i.e. neither red nor green) - this is why the house always win on average.

Suggest your coding competition is scrapped in favour of reading 'Probabilities for Dummies'

No shit, Sherlock. This is a tongue-in-cheek article prompting us to write some wtf code.

Check your aspie's at the door next time before you go off on a rant.

• Stephen Ball (unregistered)

Quickly in Ruby (assumes no minimum bet):

```class RouletteTable
def initialize
wheel = [].fill('black',0,18)
wheel.concat([].fill('red', 0, 18))
wheel.concat(['green', 'green'])
@wheel = wheel
@counter = []
end

def spin
@counter << @wheel[rand(@wheel.size)]
return @counter[-1]
end

def lastFour
return @counter[-4 .. -1]
end

def lastColor
return @counter[-1]
end
end

def perch(startingBankroll, numberOfTables, desiredBankroll)
currentBankroll = startingBankroll
tables = []
1.upto(numberOfTables) { |n| tables << RouletteTable.new() }
# build up some table history
1.upto(10) { |n| tables.each { |table| table.spin } }

while currentBankroll > 0 and currentBankroll < desiredBankroll
# spin each table
tables.each { |table| table.spin }

# check each table
puts "Checking tables"
tables.each_with_index do |table, i|
if table.lastFour.uniq.length == 1
# table is ready for a bet

# bet half our bankroll
bet = currentBankroll / 2
if bet < 0
bet = currentBankroll
end

# bet the opposite color of the series
if table.lastColor == 'black'
betColor = 'red'
else
betColor = 'black'
end

puts "Betting \$#{bet} on #{betColor} on Table #{i + 1}"
if table.spin == betColor
# we won!
currentBankroll += bet
puts "We won! \$#{currentBankroll}"
break;
else
# we lost once :-(
currentBankroll -= bet
puts "We lost once: \$#{currentBankroll}"
# now there is a five in a row, so up the bet
bet += bet / 2
if bet > currentBankroll
bet = currentBankroll
end
puts "Second bet is \$#{bet}"
if table.spin == betColor
# ca-ching!
currentBankroll += bet
puts "We won the second time: \$#{currentBankroll}"
else
# we lost twice, stupid table
currentBankroll -= bet
puts "We lost twice: \$#{currentBankroll}"
end
end # if we won the first spin
end # if table has four in a row
end # table loop
end # while bankroll is more than zero and less than desired
return currentBankroll
end # perch

puts perch(10, 4, 400)
```

Actually, you can regularly win at gambling - if you own the casino.

• (cs)

TRWTF is why anyone would write a program when it can (and should) be solved analytically. This is a random walk process. A random walk has a zero mean and a variance that grows as O(sqrt t). Every random walk will eventually cross the +400 mark, but the time to do that is a random function, and there is also a finite probability of crossing the -1,000,000 mark before that time.

http://en.wikipedia.org/wiki/Random_walk

• (cs)

It'll be tough to test The Perch without a properly balanced roulette wheel. Here is one coded in Python:

```import random

wheel = [-1] * 18 + [0] * 2 + [+1] * 18

def roulette():
# Return the color chosen by a spin of a roulette wheel:
# -1 (black), +1 (red), or 0 (green)
random.shuffle(wheel)
spin = wheel.pop()
wheel.append(-spin)  # maintain balance
return spin

if __name__ == '__main__':
# Test the roulette wheel
count = [ 0, 0, 0 ]
for i in range(380):
spin = roulette()
count[spin] += 1
print ('green',' red ','black')[spin]
print "Spun %i black, %i red, %i green" % (count[-1], count[1], count[0])
print "Expected 180 black, 180 red, 20 green"
```
• Vin (unregistered) in reply to Daniel

'The odds' refers to the payout in this instance. A \$10 bet pays out \$10 winnings plus your \$10 stake retued = \$20.

• BG (unregistered) in reply to Roflo

0 and 00 are there to tip the odds in favor of the house. You can bet on them but all computations are based on there being only 36 outcomes.

0 and 00 pay of 36:1 green pays off 18:1

• Boden (unregistered) in reply to There is so much WTF in this I don't know where to start

If only it were so simple.

Here's an interesting article: http://mathworld.wolfram.com/CoinTossing.html