Jonathan D. Storm hai 3 meses
pai
achega
503f7bfe00
Modificáronse 3 ficheiros con 136 adicións e 0 borrados
  1. 103 0
      cmd/day_3/main.go
  2. 32 0
      cmd/day_3/main_test.go
  3. 1 0
      cmd/day_3/test.txt

+ 103 - 0
cmd/day_3/main.go

@@ -0,0 +1,103 @@
+package main
+
+import (
+	"bufio"
+	"errors"
+	"fmt"
+	"io"
+	"log"
+	"os"
+)
+
+func isDigit(b byte) bool {
+	if '0' <= b && b <= '9' {
+		return true
+	}
+	return false
+}
+
+type State struct {
+	buf []byte
+	a   []byte
+	b   []byte
+	sum int
+}
+
+func (st *State) Reset() {
+	st.buf = st.buf[:0]
+	st.a = st.a[:0]
+	st.b = st.b[:0]
+}
+
+func main() {
+	r := bufio.NewReader(os.Stdin)
+	fmt.Println(process(r))
+}
+
+func process(r *bufio.Reader) int {
+	st := State{
+		buf: make([]byte, 0, 16),
+		a:   make([]byte, 0, 3),
+		b:   make([]byte, 0, 3),
+	}
+	for {
+		e, err := r.ReadByte()
+		if errors.Is(err, io.EOF) {
+			break
+		}
+		if err != nil {
+			log.Fatalf("Unable to read input: %v", err)
+		}
+		event(&st, e)
+	}
+	return st.sum
+}
+
+func event(st *State, e byte) {
+	switch {
+	case len(st.buf) == 5 && e == ')':
+		if len(st.a) == 0 || len(st.b) == 0 {
+			st.Reset()
+			break
+		}
+		s := 1
+		for j, c := range st.a {
+			if j > 0 {
+				s *= 10
+			}
+			ss := s
+			for k, d := range st.b {
+				if k > 0 {
+					ss *= 10
+				}
+				sum := int(c) * int(d) * ss
+				st.sum += sum
+			}
+		}
+		st.Reset()
+
+	case len(st.buf) == 5 && isDigit(e):
+		if len(st.a) == 3 {
+			st.Reset()
+			break
+		}
+		st.b = append(st.b, e-48)
+
+	case len(st.buf) == 4 && isDigit(e):
+		if len(st.a) == 3 {
+			st.Reset()
+			break
+		}
+		st.a = append(st.a, e-48)
+
+	case len(st.buf) == 4 && e == ',' ||
+		len(st.buf) == 3 && e == '(' ||
+		len(st.buf) == 2 && e == 'l' ||
+		len(st.buf) == 1 && e == 'u' ||
+		len(st.buf) == 0 && e == 'm':
+		st.buf = append(st.buf, e)
+
+	default:
+		st.Reset()
+	}
+}

+ 32 - 0
cmd/day_3/main_test.go

@@ -0,0 +1,32 @@
+package main
+
+import (
+	"bufio"
+	"bytes"
+	"testing"
+)
+
+func TestCorrupted(t *testing.T) {
+	cases := []struct {
+		Name     string
+		Expected int
+		Input    string
+	}{
+		{"example", 161, "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))"},
+		{"intact1", 6, "mul(2,3)"},
+		{"corrupt1", 0, "mul(4*"},
+		{"corrupt2", 0, "mul(6,9!"},
+		{"corrupt3", 0, "?(12,34)"},
+		{"corrupt4", 0, "mul ( 2 , 4 )"},
+	}
+	for _, c := range cases {
+		buf := new(bytes.Buffer)
+		buf.WriteString(c.Input)
+		r := bufio.NewReader(buf)
+
+		actual := process(r)
+		if actual != c.Expected {
+			t.Errorf("Expected %d; got %d", c.Expected, actual)
+		}
+	}
+}

+ 1 - 0
cmd/day_3/test.txt

@@ -0,0 +1 @@
+xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))