Created
February 14, 2013 07:53
-
-
Save oyms/4951217 to your computer and use it in GitHub Desktop.
Casino
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
public static void Main() | |
{ | |
const int tries = 10000; | |
const double prize = 36D; | |
const double propabilityOfSuccess = (1D / 37D); | |
const double initialBet = 1D; | |
var c = new Casino(prize, propabilityOfSuccess); | |
var results=c.Run(initialBet, tries); | |
foreach (var result in results) | |
{ | |
Console.WriteLine(result.ToString()); | |
} | |
Console.WriteLine("Total winning: "+results.Sum(r=>r.Winnings)); | |
Console.WriteLine("Number of bets: "+results.Sum(r=>r.NumberOfBets)); | |
Console.WriteLine("Max amount: "+results.Max(r=>r.Bet)); | |
Console.ReadKey(); | |
} | |
class Casino | |
{ | |
private readonly double prize; | |
private readonly double p; | |
private readonly Random rnd; | |
public Casino(double prize, double propabilityOfSuccess) | |
{ | |
this.prize = prize; | |
p = propabilityOfSuccess; | |
rnd = new Random(); | |
} | |
public IEnumerable<Result> Run(double initalBet, int tries) | |
{ | |
for (int i = 0; i < tries; i++) | |
{ | |
yield return Bet(new Result (i){Bet = initalBet, NumberOfBets = 0},0); | |
} | |
} | |
private Result Bet(Result result,double sunkenCost) | |
{ | |
var bet = result.Bet; | |
result.NumberOfBets++; | |
if (Draw()) | |
{ | |
result.Winnings = (bet*prize) - (bet + sunkenCost); | |
return result; | |
} | |
result.Bet = (bet * prize) / (prize - 1); | |
return Bet(result, sunkenCost + bet); | |
} | |
private bool Draw() | |
{ | |
return rnd.NextDouble() < p; | |
} | |
} | |
class Result | |
{ | |
public Result(int index) | |
{ | |
Index = index; | |
} | |
private int Index { get; set; } | |
public double Winnings { get; set; } | |
public int NumberOfBets { get; set; } | |
public double Bet { get; set; } | |
public override string ToString() | |
{ | |
return string.Format("{0}: {1}{2}{3}", Index.ToString(), Winnings.ToString(), new string('.', NumberOfBets), Bet.ToString()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment