refactor with filter() and byName()

This commit is contained in:
onyx-and-iris 2024-12-26 13:12:48 +00:00
parent 4aaf594e23
commit 24bb0d40c9

View File

@ -2,42 +2,28 @@ package one
import ( import (
"bytes" "bytes"
"cmp" "sort"
"slices"
"strconv" "strconv"
"strings" "strings"
log "github.com/sirupsen/logrus"
) )
func Solve(buf []byte) (int, error) { func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf) r := bytes.NewReader(buf)
initial, wires, expressions, err := parseLines(r) wires, expressions, err := parseLines(r)
if err != nil { if err != nil {
return 0, err return 0, err
} }
for k, v := range initial {
wires[k] = v
}
wires = calculateWire(expressions, wires) wires = calculateWire(expressions, wires)
zWires := filter(wires, func(name string) bool {
zWires := []zWire{} return strings.HasPrefix(name, "z")
for k, v := range wires {
if strings.HasPrefix(k, "z") {
zWires = append(zWires, zWire{k, v})
}
}
slices.SortFunc(zWires, func(a, b zWire) int {
return cmp.Compare(b.name, a.name)
}) })
sort.Sort(byName(zWires))
var binStr strings.Builder var binStr strings.Builder
for _, zWire := range zWires { for _, zWire := range zWires {
binStr.WriteString(strconv.FormatInt(int64(zWire.value), 2)) binStr.WriteString(strconv.Itoa(zWire.value))
} }
log.Debug(binStr.String())
return mustConvBinToDec(binStr.String()), nil return mustConvBinToDec(binStr.String()), nil
} }