From 81f11c52ef9ee2ecfe07a9b39c1d8767fade23a7 Mon Sep 17 00:00:00 2001 From: Gregory Date: Tue, 8 Feb 2022 21:38:01 +0200 Subject: [PATCH] d3 --- d3/d3.go | 38 ++++++++++++++++++++++++++++++++++++++ d3/d3_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 d3/d3.go create mode 100644 d3/d3_test.go diff --git a/d3/d3.go b/d3/d3.go new file mode 100644 index 0000000..f7d9905 --- /dev/null +++ b/d3/d3.go @@ -0,0 +1,38 @@ +package d3 + +import ( + "strconv" + "strings" +) + +func D3(input string) int64 { + binaries := strings.Split(strings.TrimSpace(input), "\n") + + ones := make([]int, len(binaries[0])) + + for _, binary := range binaries { + for position, bit := range binary { + if byte(bit) == '1' { + ones[position]++ + } + } + } + + gamma := make([]string, len(ones)) + epsilon := make([]string, len(ones)) + + for pos, oneCount := range ones { + if oneCount > len(binaries)/2 { + gamma[pos] = "1" + epsilon[pos] = "0" + } else { + gamma[pos] = "0" + epsilon[pos] = "1" + } + } + + gammaNum, _ := strconv.ParseInt(strings.Join(gamma, ""), 2, 64) + epsilonNum, _ := strconv.ParseInt(strings.Join(epsilon, ""), 2, 64) + + return gammaNum * epsilonNum +} diff --git a/d3/d3_test.go b/d3/d3_test.go new file mode 100644 index 0000000..9a0e844 --- /dev/null +++ b/d3/d3_test.go @@ -0,0 +1,25 @@ +package d3 + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestD3(t *testing.T) { + input := ` +00100 +11110 +10110 +10111 +10101 +01111 +00111 +11100 +10000 +11001 +00010 +01010` + + assert.EqualValues(t, 198, D3(input)) +}