day14.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. var mem map[int64]int64
  10. var mask string
  11. const (
  12. maskMaxIndex = 35
  13. )
  14. func setBits(number int64, mask string) int64 {
  15. for i := 0; i <= maskMaxIndex; i++ {
  16. switch mask[maskMaxIndex-i] {
  17. case 'X':
  18. continue
  19. case '1':
  20. number |= (1 << i)
  21. case '0':
  22. var tempMask int64
  23. tempMask = ^(1 << i)
  24. number &= tempMask
  25. }
  26. }
  27. return number
  28. }
  29. func processLine(line string) error {
  30. if strings.Contains(line, "mask") {
  31. n, err := fmt.Sscanf(line, "mask = %s\n", &mask)
  32. if err != nil || n != 1 {
  33. return fmt.Errorf("Error scanning '%s': %s", line, err)
  34. }
  35. return nil
  36. }
  37. var id int64
  38. var number int64
  39. n, err := fmt.Sscanf(line, "mem[%d] = %d", &id, &number)
  40. if err != nil || n != 2 {
  41. return fmt.Errorf("Error scanning '%s': %s", line, err)
  42. }
  43. number = setBits(number, mask)
  44. mem[id] = number
  45. return nil
  46. }
  47. func readFile(file *os.File) {
  48. scanner := bufio.NewScanner(file)
  49. for scanner.Scan() {
  50. line := scanner.Text()
  51. if line == "" {
  52. break
  53. }
  54. if err := processLine(line); err != nil {
  55. log.Fatal(err)
  56. }
  57. }
  58. if err := scanner.Err(); err != nil {
  59. log.Fatalf("Scanner error: %s", err)
  60. }
  61. }
  62. func sum() int64 {
  63. var sum int64
  64. for _, value := range mem {
  65. sum += value
  66. }
  67. return sum
  68. }
  69. func init() {
  70. mem = make(map[int64]int64)
  71. }
  72. func main() {
  73. if len(os.Args) < 2 {
  74. log.Fatal("You need to specify a file!")
  75. }
  76. file, err := os.Open(os.Args[1])
  77. if err != nil {
  78. log.Fatalf("Failed to open %s!\n", os.Args[1])
  79. }
  80. readFile(file)
  81. if err := file.Close(); err != nil {
  82. log.Fatalf("Failed to close file: %s", err)
  83. }
  84. fmt.Println("Part1:", sum())
  85. }