Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 14
Good morning! Here's your coding interview problem for today.

This problem was asked by Google.

The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.

Hint: The basic equation of a circle is x^2 + y^2 = r^2.

Pull request:
day 14 solution. based on randomization so there is a chance of test …
…failure

Resolves #31 

Patch:
diff --git a/README.md b/README.md
index c2c490e..e75b4d3 100644
--- a/README.md
+++ b/README.md
@@ -24,3 +24,4 @@ problems from
 * [Day 12](https://github.com/vaskoz/dailycodingproblem-go/issues/25)
 * [Day 12 Count and Deepest](https://github.com/vaskoz/dailycodingproblem-go/issues/27)
 * [Day 13](https://github.com/vaskoz/dailycodingproblem-go/issues/29)
+* [Day 14](https://github.com/vaskoz/dailycodingproblem-go/issues/31)
diff --git a/day14/problem.go b/day14/problem.go
new file mode 100644
index 0000000..9cd144f
--- /dev/null
+++ b/day14/problem.go
@@ -0,0 +1,20 @@
+package day14
+
+import (
+	"math/rand"
+	"time"
+)
+
+// EstimatePi uses monte carlo simulation to estimate PI.
+func EstimatePi(iterations int) float64 {
+	rand.Seed(time.Now().UnixNano())
+	var inCircle, total int
+	for total = 0; total < iterations; total++ {
+		x := rand.Float64()
+		y := rand.Float64()
+		if x*x+y*y <= 1 {
+			inCircle++
+		}
+	}
+	return 4.0 * float64(inCircle) / float64(total)
+}


Test patch:
diff --git a/day14/problem_test.go b/day14/problem_test.go
new file mode 100644
index 0000000..27dcc46
--- /dev/null
+++ b/day14/problem_test.go
@@ -0,0 +1,33 @@
+package day14
+
+import (
+	"math"
+	"testing"
+)
+
+var testcases = []struct {
+	iterations int
+	expected   float64
+	delta      float64
+}{
+	{100000, 3.1415, 0.1},
+	{10000, 3.1415, 0.1},
+	{1000, 3.1415, 0.1},
+}
+
+func TestEstimatePi(t *testing.T) {
+	t.Parallel()
+	for _, tc := range testcases {
+		if pi := EstimatePi(tc.iterations); math.Abs(pi-tc.expected) > tc.delta {
+			t.Errorf("Expected %v but got %v with delta %v", tc.expected, pi, tc.delta)
+		}
+	}
+}
+
+func BenchmarkEstimatePi(b *testing.B) {
+	for i := 0; i < b.N; i++ {
+		for _, tc := range testcases {
+			EstimatePi(tc.iterations)
+		}
+	}
+}