diff --git a/03/main.go b/03/main.go new file mode 100644 index 0000000..92b328b --- /dev/null +++ b/03/main.go @@ -0,0 +1,66 @@ +package main + +import ( + "bufio" + "fmt" + "math/bits" + "os" + "strconv" + "time" +) + +func main() { + start := time.Now() + partOne() + duration := time.Since(start) + partTwo() + duration2 := time.Since(start) + fmt.Printf("p1: %s, p2: %s\n", duration, duration2-duration) +} + +func makeScanner(test bool) *bufio.Scanner { + var f *os.File + if test { + f, _ = os.Open("inputs/testinput") + } else { + f, _ = os.Open("inputs/input") + } + reader := bufio.NewReader(f) + return bufio.NewScanner(reader) +} + +func partOne() { + scanner := makeScanner(false) + + r := map[int]int64{} // index => count of 1s + var lines int64 + + for scanner.Scan() { + line := scanner.Text() + lines++ + n, _ := strconv.ParseInt(line, 2, 64) + for i := 0; i < bits.Len(uint(n)); i++ { + // check if the number in the i'th column is 1, then bit-shift back to the 1s place to add it if it is + r[i] += (n & (1 << i)) >> i + } + } + var epsilon, gamma int64 + for i, b := range r { + // if more than half the bits were ones, gamma gets the 1, otherwise epsilon gets the 1 + // alternatively, this could have been an XOR operation, I suppose, once one or the other had been computed + if b > lines/2 { + gamma += 1 << i + } else { + epsilon += 1 << i + } + } + fmt.Println(epsilon * gamma) +} + +func partTwo() { + scanner := makeScanner(false) + + for scanner.Scan() { + // line := scanner.Text() + } +}