From b3827cf53adbc2b542d66d865874be3b9aee5b80 Mon Sep 17 00:00:00 2001 From: Luke Else Date: Fri, 3 Dec 2021 21:04:10 +0000 Subject: [PATCH] day 3b complete --- day3/3b/go.mod | 3 ++ day3/3b/main.go | 96 +++++++++++++++++++++++++++++++++++++++++++++++ day3/3b/testInput | 12 ++++++ 3 files changed, 111 insertions(+) create mode 100644 day3/3b/go.mod create mode 100644 day3/3b/main.go create mode 100644 day3/3b/testInput diff --git a/day3/3b/go.mod b/day3/3b/go.mod new file mode 100644 index 0000000..e938e2e --- /dev/null +++ b/day3/3b/go.mod @@ -0,0 +1,3 @@ +module PWD + +go 1.17 diff --git a/day3/3b/main.go b/day3/3b/main.go new file mode 100644 index 0000000..18d0aed --- /dev/null +++ b/day3/3b/main.go @@ -0,0 +1,96 @@ +package main + +import ( + "bufio" + "fmt" + "math" + "os" +) + +func main() { + content := returnContent("../input") + + //content := returnContent("testInput") + + oxygen, carbon := findOxygenAndCarbon(content, 0) + + fmt.Println(oxygen, carbon) + + fmt.Println(binaryToInteger(oxygen) * binaryToInteger(carbon)) +} + +func findOxygenAndCarbon(content *[]string, i int) (oxygen string, carbon string) { + //recursion + + oxygen = (*findValues(content, 0, true))[0] + + carbon = (*findValues(content, 0, false))[0] + + return +} + +//recursively find the values that fit the criteria +func findValues(content *[]string, i int, inclusive bool) (values *[]string) { + + if len(*content) <= 1 { + return content + } + + count := 0 + var bit byte = '0' + for j := 0; j < len(*content); j++ { + if ((*content)[j])[i] == '1' { + count++ + } + } + + if inclusive { + if float64(count) >= float64(len(*content))/2 { + bit = '1' + } + } else { + if float64(count) < float64(len(*content))/2 { + bit = '1' + } + } + + var newContent []string + for j := 0; j < len(*content); j++ { + if ((*content)[j])[i] == bit { + newContent = append(newContent, (*content)[j]) + } + } + i++ + return findValues(&newContent, i, inclusive) +} + +func binaryToInteger(input string) (value int) { + n := 0 + for i := len(input) - 1; i >= 0; i-- { + if input[i] == '1' { + value += (int(math.Pow(float64(2), float64(n)))) + } + n++ + } + return +} + +func returnContent(path string) *[]string { + //read file and return it as an array of integers + + file, err := os.Open(path) + var content []string + + if err != nil { + fmt.Println("Unlucky, the file didn't open") + return &content + } + defer file.Close() + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + content = append(content, scanner.Text()) + } + + return &content +} diff --git a/day3/3b/testInput b/day3/3b/testInput new file mode 100644 index 0000000..665fd57 --- /dev/null +++ b/day3/3b/testInput @@ -0,0 +1,12 @@ +00100 +11110 +10110 +10111 +10101 +01111 +00111 +11100 +10000 +11001 +00010 +01010 \ No newline at end of file