mirror of
https://github.com/tiennm99/adventofcode.git
synced 2026-10-12 14:14:43 +00:00
102 lines
1.5 KiB
Go
102 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
|
|
mapset "github.com/deckarep/golang-set/v2"
|
|
)
|
|
|
|
func main() {
|
|
f, err := os.Open("input.txt")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
defer f.Close()
|
|
|
|
scanner := bufio.NewScanner(f)
|
|
|
|
totalPresses := 0
|
|
|
|
for scanner.Scan() {
|
|
line := strings.TrimSpace(scanner.Text())
|
|
if line == "" {
|
|
continue
|
|
}
|
|
|
|
parts := strings.Fields(line)
|
|
if len(parts) < 3 {
|
|
continue
|
|
}
|
|
|
|
diagram := parts[0]
|
|
|
|
pattern := diagram[1 : len(diagram)-1]
|
|
want := 0
|
|
for i := 0; i < len(pattern); i++ {
|
|
if pattern[i] == '#' {
|
|
want |= (1 << i)
|
|
}
|
|
}
|
|
|
|
var have []int
|
|
for i := 1; i < len(parts)-1; i++ {
|
|
btn := parts[i]
|
|
content := btn[1 : len(btn)-1]
|
|
if len(content) == 0 {
|
|
continue
|
|
}
|
|
fields := strings.Split(content, ",")
|
|
mask := 0
|
|
for _, f := range fields {
|
|
idx, err := strconv.Atoi(f)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
mask |= (1 << idx)
|
|
}
|
|
have = append(have, mask)
|
|
}
|
|
|
|
type node struct {
|
|
cost int
|
|
val int
|
|
}
|
|
|
|
queue := []node{{0, 0}}
|
|
visited := mapset.NewSet[int]()
|
|
visited.Add(0)
|
|
|
|
foundCost := -1
|
|
|
|
for len(queue) > 0 {
|
|
cur := queue[0]
|
|
queue = queue[1:]
|
|
|
|
if cur.val == want {
|
|
foundCost = cur.cost
|
|
break
|
|
}
|
|
|
|
for _, b := range have {
|
|
nv := cur.val ^ b
|
|
if !visited.Contains(nv) {
|
|
visited.Add(nv)
|
|
queue = append(queue, node{cur.cost + 1, nv})
|
|
}
|
|
}
|
|
}
|
|
|
|
if foundCost < 0 {
|
|
panic("no solution found for a machine")
|
|
}
|
|
|
|
totalPresses += foundCost
|
|
}
|
|
|
|
fmt.Println(totalPresses)
|
|
}
|