53 lines
1.6 KiB
Go
53 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"strings"
|
|
"strconv"
|
|
"io/ioutil"
|
|
"fmt"
|
|
"regexp"
|
|
)
|
|
|
|
func main() {
|
|
mem := make(map[int64]int64) // The values are 36-bit - using int64s
|
|
memre, _ := regexp.Compile(`mem\[(\d+)\] = (\d+)`) // isn't matching all memory lines?
|
|
maskre, _ := regexp.Compile(`mask = ([01X]+)`)
|
|
d, _ := ioutil.ReadFile("input")
|
|
lines := strings.Split(string(d),"\n")
|
|
var mask string
|
|
for _, l := range lines {
|
|
memMatch := memre.FindStringSubmatch(l)
|
|
maskMatch := maskre.FindStringSubmatch(l)
|
|
if len(memMatch) != 0 {
|
|
addr, _ := strconv.ParseInt(memMatch[1], 10, 64)
|
|
value, _ := strconv.ParseInt(memMatch[2], 10, 64)
|
|
|
|
// Applying the bitmask using strings because I'm doing this the stupid way
|
|
valueString := strconv.FormatInt(value, 2) // value as a binary string
|
|
v := ""
|
|
// Pad out to 36 bits
|
|
for i := 36-len(valueString); i > 0; i-- {
|
|
v = "0" + v
|
|
}
|
|
v = v + valueString
|
|
applied := ""
|
|
for i, _ := range v {
|
|
if mask[i] != byte('X') {
|
|
applied += string(mask[i])
|
|
} else {
|
|
applied += string(v[i])
|
|
}
|
|
}
|
|
av, _:= strconv.ParseInt(applied, 2, 64) // applied
|
|
mem[addr] = av
|
|
} else if len(maskMatch) != 0 {
|
|
mask = maskMatch[1]
|
|
} else {}
|
|
}
|
|
var sum int64 = 0
|
|
for _, v := range mem {
|
|
sum += v
|
|
}
|
|
fmt.Println("Part 1:", sum)
|
|
}
|