Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 210
Good morning! Here's your coding interview problem for today.

This problem was asked by Apple.

A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer:

if n is even, the next number in the sequence is n / 2
if n is odd, the next number in the sequence is 3n + 1
It is conjectured that every such sequence eventually reaches the number 1. Test this conjecture.

Bonus: What input n <= 1000000 gives the longest sequence?

Pull request description:
Day210
Resolves #432.

Patch:
diff --git a/README.md b/README.md
index 1d6ba77..57c9f14 100644
--- a/README.md
+++ b/README.md
@@ -219,3 +219,4 @@ problems from
 * [Day 206](https://github.com/vaskoz/dailycodingproblem-go/issues/424)
 * [Day 207](https://github.com/vaskoz/dailycodingproblem-go/issues/426)
 * [Day 208](https://github.com/vaskoz/dailycodingproblem-go/issues/427)
+* [Day 210](https://github.com/vaskoz/dailycodingproblem-go/issues/432)
diff --git a/day210/problem.go b/day210/problem.go
new file mode 100644
index 0000000..4004c39
--- /dev/null
+++ b/day210/problem.go
@@ -0,0 +1,25 @@
+package day210
+
+// LongestCollatzSequence returns the number with the longest
+// sequence.
+// First result is the number, second number is the length of the sequence.
+func LongestCollatzSequence(max int) (int, int) {
+	var n, longest int
+	for i := max; i > 0; i-- {
+		count := 0
+		v := i
+		for v != 1 {
+			if v%2 == 0 {
+				v /= 2
+			} else {
+				v = 3*v + 1
+			}
+			count++
+		}
+		if count > longest {
+			longest = count
+			n = i
+		}
+	}
+	return n, longest
+}


Test patch:
diff --git a/day210/problem_test.go b/day210/problem_test.go
new file mode 100644
index 0000000..e4eaad6
--- /dev/null
+++ b/day210/problem_test.go
@@ -0,0 +1,28 @@
+package day210
+
+import (
+	"testing"
+)
+
+func TestLongestCollatzSequence(t *testing.T) {
+	t.Parallel()
+	t.Skip("unskip test to verify result. takes too long to run")
+	n, length := LongestCollatzSequence(1000000)
+	if n != 837799 || length != 524 {
+		t.Errorf("Expected (837799,524), got (%v,%v)", n, length)
+	}
+}
+
+func TestLongestCollatzSequenceSmaller(t *testing.T) {
+	t.Parallel()
+	n, length := LongestCollatzSequence(10)
+	if n != 9 || length != 19 {
+		t.Errorf("Expected (9, 19), got (%v,%v)", n, length)
+	}
+}
+
+func BenchmarkLongestCollatzSequence(b *testing.B) {
+	for i := 0; i < b.N; i++ {
+		LongestCollatzSequence(10)
+	}
+}