day 3 part 1

This commit is contained in:
David 2021-12-03 10:11:54 -05:00
parent 4b22135336
commit 91383fc6b0
1 changed files with 66 additions and 0 deletions

66
03/main.go Normal file
View File

@ -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()
}
}