Created
February 14, 2012 23:11
-
-
Save jongyllen/1831466 to your computer and use it in GitHub Desktop.
Greg Young Probability kata proposed solution #1
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 NUnit.Framework; | |
namespace ProbabilityKata | |
{ | |
[TestFixture] | |
public class ProbabilityTests | |
{ | |
[Test] | |
public void CanCompareTwoEqualProbabilities() | |
{ | |
var p1 = new Probability(1); | |
var p2 = new Probability(1); | |
Assert.AreEqual(p1,p2); | |
} | |
[Test] | |
public void CanCompareTwoNotEqualProbabilities() | |
{ | |
var p1 = new Probability(1); | |
var p2 = new Probability(0.9f); | |
Assert.AreNotEqual(p1, p2); | |
} | |
[Test] | |
public void CanCombineProbabilities() | |
{ | |
var p1 = new Probability(0.9f); | |
var p2 = new Probability(0.9f); | |
Assert.AreEqual(p1.CombinedWith(p2), new Probability(0.81f)); | |
} | |
[Test] | |
public void CanInverseOfProbabilities() | |
{ | |
var p1 = new Probability(0.9f); | |
Assert.AreEqual(p1.InverseOf(p1), new Probability(0.1f)); | |
} | |
[Test] | |
public void CanEitherOfProbabilities() | |
{ | |
var p1 = new Probability(0.9f); | |
var p2 = new Probability(0.5f); | |
Assert.AreEqual(p1.Either(p2), new Probability(0.95f)); | |
} | |
} | |
public class Probability | |
{ | |
private readonly float _probability; | |
private const double Epsilon = 0.001; | |
public Probability(float probability) | |
{ | |
_probability = probability; | |
} | |
public Probability CombinedWith(Probability p) | |
{ | |
return new Probability(p._probability * _probability); | |
} | |
public Probability InverseOf(Probability p) | |
{ | |
return new Probability(1 - p._probability); | |
} | |
public Probability Either(Probability p) | |
{ | |
return new Probability(_probability+p._probability - _probability * p._probability); | |
} | |
public override string ToString() | |
{ | |
return "P(" + _probability + ")"; | |
} | |
public bool Equals(Probability other) | |
{ | |
if (ReferenceEquals(null, other)) return false; | |
if (ReferenceEquals(this, other)) return true; | |
return Math.Abs(other._probability - _probability) < Epsilon; | |
} | |
public override bool Equals(object obj) | |
{ | |
if (obj == null || !(obj is Probability)) | |
return false; | |
return Equals((Probability) obj); | |
} | |
public override int GetHashCode() | |
{ | |
return _probability.GetHashCode(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment