mirror of
https://github.com/onyx-and-iris/aoc2024.git
synced 2026-04-09 02:23:36 +00:00
add day-18 + benchmarks
This commit is contained in:
7
day-18/internal/config/config.go
Normal file
7
day-18/internal/config/config.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package config
|
||||
|
||||
type Config struct {
|
||||
Width int
|
||||
Height int
|
||||
NumCorruptions int
|
||||
}
|
||||
6
day-18/internal/one/benchmark
Normal file
6
day-18/internal/one/benchmark
Normal file
@@ -0,0 +1,6 @@
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
pkg: github.com/onyx-and-iris/aoc2024/day-18/internal/one
|
||||
cpu: Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
|
||||
BenchmarkSolve-12 1000000000 0.004050 ns/op
|
||||
ok github.com/onyx-and-iris/aoc2024/day-18/internal/one 0.029s
|
||||
50
day-18/internal/one/graph.go
Normal file
50
day-18/internal/one/graph.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package one
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type graph struct {
|
||||
start Point
|
||||
end Point
|
||||
data []string
|
||||
}
|
||||
|
||||
func newGraph(width, height, numCorruptions int, corruptedCoords [][]int) *graph {
|
||||
var data []string
|
||||
var sb strings.Builder
|
||||
for range height {
|
||||
for range width {
|
||||
sb.WriteRune('.')
|
||||
}
|
||||
data = append(data, sb.String())
|
||||
sb.Reset()
|
||||
}
|
||||
|
||||
for _, coords := range corruptedCoords[:numCorruptions] {
|
||||
data[coords[1]] = replaceAtIndex(data[coords[1]], '#', coords[0])
|
||||
}
|
||||
|
||||
return &graph{Point{0, 0}, Point{len(data[0]) - 1, len(data) - 1}, data}
|
||||
}
|
||||
|
||||
func (g *graph) String() string {
|
||||
return strings.Join(g.data, "\n")
|
||||
}
|
||||
|
||||
func (g *graph) isOutOfBounds(p Point) bool {
|
||||
return p.X < 0 || p.Y < 0 || p.Y >= len(g.data) || p.X >= len(g.data[p.Y])
|
||||
}
|
||||
|
||||
func (g *graph) valueAt(p Point) rune {
|
||||
return rune(g.data[p.Y][p.X])
|
||||
}
|
||||
|
||||
func (g *graph) debug(path []Point) string {
|
||||
temp := slices.Clone(g.data)
|
||||
for _, p := range path {
|
||||
temp[p.Y] = replaceAtIndex(temp[p.Y], 'O', p.X)
|
||||
}
|
||||
return strings.Join(temp, "\n")
|
||||
}
|
||||
10
day-18/internal/one/neighbours.go
Normal file
10
day-18/internal/one/neighbours.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package one
|
||||
|
||||
func neighbours(p Point) [4]Point {
|
||||
return [4]Point{
|
||||
{p.X, p.Y - 1}, // N
|
||||
{p.X + 1, p.Y}, // E
|
||||
{p.X, p.Y + 1}, // S
|
||||
{p.X - 1, p.Y}, // W
|
||||
}
|
||||
}
|
||||
6
day-18/internal/one/point.go
Normal file
6
day-18/internal/one/point.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package one
|
||||
|
||||
type Point struct {
|
||||
X int
|
||||
Y int
|
||||
}
|
||||
76
day-18/internal/one/solve.go
Normal file
76
day-18/internal/one/solve.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package one
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
|
||||
"github.com/onyx-and-iris/aoc2024/day-18/internal/config"
|
||||
"github.com/onyx-and-iris/aoc2024/day-18/internal/queue"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var ShortestPath []Point
|
||||
|
||||
func Solve(buf []byte, config config.Config) (int, error) {
|
||||
r := bytes.NewReader(buf)
|
||||
graph, err := parseLines(r, config)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
log.Debugf("start: %v end: %v", graph.start, graph.end)
|
||||
|
||||
log.Debugf("\n%s\n", graph.String())
|
||||
queue := queue.New[Point]()
|
||||
queue.Enqueue(graph.start)
|
||||
visited := make(map[Point]struct{})
|
||||
costs := make(map[Point]int)
|
||||
prev := make(map[Point]Point)
|
||||
|
||||
for !queue.IsEmpty() {
|
||||
current := queue.Dequeue()
|
||||
|
||||
if current == graph.end {
|
||||
break
|
||||
}
|
||||
|
||||
_, ok := visited[current]
|
||||
if ok {
|
||||
continue
|
||||
}
|
||||
visited[current] = struct{}{}
|
||||
|
||||
for _, n := range neighbours(current) {
|
||||
if graph.isOutOfBounds(n) {
|
||||
continue
|
||||
}
|
||||
|
||||
if graph.valueAt(n) == '#' {
|
||||
continue
|
||||
}
|
||||
|
||||
_, ok := costs[n]
|
||||
if !ok {
|
||||
costs[n] = math.MaxInt
|
||||
}
|
||||
|
||||
new_cost := costs[current] + 1
|
||||
if new_cost < costs[n] {
|
||||
costs[n] = new_cost
|
||||
prev[n] = current
|
||||
queue.Enqueue(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ShortestPath = []Point{graph.end}
|
||||
node := prev[graph.end]
|
||||
for node != graph.start {
|
||||
ShortestPath = append(ShortestPath, prev[node])
|
||||
node = prev[node]
|
||||
}
|
||||
|
||||
log.Debugf("\n%s\n", graph.debug(ShortestPath))
|
||||
|
||||
return len(ShortestPath), nil
|
||||
}
|
||||
21
day-18/internal/one/solve_internal_test.go
Normal file
21
day-18/internal/one/solve_internal_test.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package one
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/onyx-and-iris/aoc2024/day-18/internal/config"
|
||||
)
|
||||
|
||||
//go:embed testdata/input.txt
|
||||
var data []byte
|
||||
|
||||
func BenchmarkSolve(b *testing.B) {
|
||||
os.Stdout, _ = os.Open(os.DevNull)
|
||||
Solve(data, config.Config{
|
||||
Width: 71,
|
||||
Height: 71,
|
||||
NumCorruptions: 1024,
|
||||
})
|
||||
}
|
||||
41
day-18/internal/one/util.go
Normal file
41
day-18/internal/one/util.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package one
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/onyx-and-iris/aoc2024/day-18/internal/config"
|
||||
)
|
||||
|
||||
func parseLines(r io.Reader, config config.Config) (*graph, error) {
|
||||
corruptedCoords := [][]int{}
|
||||
scanner := bufio.NewScanner(r)
|
||||
for scanner.Scan() {
|
||||
corruptedCoords = append(corruptedCoords, func() []int {
|
||||
x := strings.Split(scanner.Text(), ",")
|
||||
return []int{mustConv(x[0]), mustConv(x[1])}
|
||||
}())
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newGraph(config.Width, config.Height, config.NumCorruptions, corruptedCoords), nil
|
||||
}
|
||||
|
||||
func mustConv(s string) int {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func replaceAtIndex(s string, r rune, i int) string {
|
||||
out := []rune(s)
|
||||
out[i] = r
|
||||
return string(out)
|
||||
}
|
||||
40
day-18/internal/queue/queue.go
Normal file
40
day-18/internal/queue/queue.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package queue
|
||||
|
||||
import "sync"
|
||||
|
||||
type ConcurrentQueue[T comparable] struct {
|
||||
items []T
|
||||
lock sync.Mutex
|
||||
cond *sync.Cond
|
||||
}
|
||||
|
||||
func New[T comparable]() *ConcurrentQueue[T] {
|
||||
q := &ConcurrentQueue[T]{}
|
||||
q.cond = sync.NewCond(&q.lock)
|
||||
return q
|
||||
}
|
||||
|
||||
func (q *ConcurrentQueue[T]) Enqueue(item T) {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
|
||||
q.items = append(q.items, item)
|
||||
q.cond.Signal()
|
||||
}
|
||||
|
||||
// Gets the item from queue
|
||||
func (q *ConcurrentQueue[T]) Dequeue() T {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
|
||||
for len(q.items) == 0 {
|
||||
q.cond.Wait()
|
||||
}
|
||||
item := q.items[0]
|
||||
q.items = q.items[1:]
|
||||
return item
|
||||
}
|
||||
|
||||
func (q *ConcurrentQueue[T]) IsEmpty() bool {
|
||||
return len(q.items) == 0
|
||||
}
|
||||
6
day-18/internal/two/benchmark
Normal file
6
day-18/internal/two/benchmark
Normal file
@@ -0,0 +1,6 @@
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
pkg: github.com/onyx-and-iris/aoc2024/day-18/internal/two
|
||||
cpu: Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
|
||||
BenchmarkSolve-12 1 3756699083 ns/op
|
||||
ok github.com/onyx-and-iris/aoc2024/day-18/internal/two 3.760s
|
||||
118
day-18/internal/two/graph.go
Normal file
118
day-18/internal/two/graph.go
Normal file
@@ -0,0 +1,118 @@
|
||||
package two
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/onyx-and-iris/aoc2024/day-18/internal/queue"
|
||||
)
|
||||
|
||||
type graph struct {
|
||||
start point
|
||||
end point
|
||||
data []string
|
||||
}
|
||||
|
||||
func newGraph(width, height, numCorruptions int, corruptedCoords [][]int) *graph {
|
||||
var data []string
|
||||
var sb strings.Builder
|
||||
for range height {
|
||||
for range width {
|
||||
sb.WriteRune('.')
|
||||
}
|
||||
data = append(data, sb.String())
|
||||
sb.Reset()
|
||||
}
|
||||
|
||||
for _, coords := range corruptedCoords[:numCorruptions] {
|
||||
data[coords[1]] = replaceAtIndex(data[coords[1]], '#', coords[0])
|
||||
}
|
||||
|
||||
return &graph{point{0, 0}, point{len(data[0]) - 1, len(data) - 1}, data}
|
||||
}
|
||||
|
||||
func (g *graph) String() string {
|
||||
return strings.Join(g.data, "\n")
|
||||
}
|
||||
|
||||
func (g *graph) isOutOfBounds(p point) bool {
|
||||
return p.x < 0 || p.y < 0 || p.y >= len(g.data) || p.x >= len(g.data[p.y])
|
||||
}
|
||||
|
||||
func (g *graph) valueAt(p point) rune {
|
||||
return rune(g.data[p.y][p.x])
|
||||
}
|
||||
|
||||
func (g *graph) addCorruption(coords []int) {
|
||||
g.data[coords[1]] = replaceAtIndex(g.data[coords[1]], '#', coords[0])
|
||||
}
|
||||
|
||||
func (g *graph) dijkstra(start, end point) ([]point, error) {
|
||||
queue := queue.New[point]()
|
||||
queue.Enqueue(start)
|
||||
visited := make(map[point]struct{})
|
||||
costs := make(map[point]int)
|
||||
prev := make(map[point]point)
|
||||
|
||||
for !queue.IsEmpty() {
|
||||
current := queue.Dequeue()
|
||||
|
||||
// we found a shortest path
|
||||
if current == end {
|
||||
return g.generatePath(start, end, prev), nil
|
||||
}
|
||||
|
||||
_, ok := visited[current]
|
||||
if ok {
|
||||
continue
|
||||
}
|
||||
visited[current] = struct{}{}
|
||||
|
||||
for _, n := range neighbours(current) {
|
||||
if g.isOutOfBounds(n) {
|
||||
continue
|
||||
}
|
||||
|
||||
if g.valueAt(n) == '#' {
|
||||
continue
|
||||
}
|
||||
|
||||
_, ok := costs[n]
|
||||
if !ok {
|
||||
costs[n] = math.MaxInt
|
||||
}
|
||||
|
||||
new_cost := costs[current] + 1
|
||||
if new_cost < costs[n] {
|
||||
costs[n] = new_cost
|
||||
prev[n] = current
|
||||
queue.Enqueue(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil, errors.New("unable to find a shortest path")
|
||||
}
|
||||
|
||||
func (g *graph) generatePath(start, end point, prev map[point]point) []point {
|
||||
path := []point{end}
|
||||
node := prev[end]
|
||||
for node != start {
|
||||
path = append(path, prev[node])
|
||||
node = prev[node]
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func (g *graph) debug(path []point) string {
|
||||
temp := slices.Clone(g.data)
|
||||
for _, p := range path {
|
||||
if g.valueAt(p) == '#' {
|
||||
continue
|
||||
}
|
||||
temp[p.y] = replaceAtIndex(temp[p.y], 'O', p.x)
|
||||
}
|
||||
return strings.Join(temp, "\n")
|
||||
}
|
||||
10
day-18/internal/two/neighbours.go
Normal file
10
day-18/internal/two/neighbours.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package two
|
||||
|
||||
func neighbours(p point) [4]point {
|
||||
return [4]point{
|
||||
{p.x, p.y - 1}, // N
|
||||
{p.x + 1, p.y}, // E
|
||||
{p.x, p.y + 1}, // S
|
||||
{p.x - 1, p.y}, // W
|
||||
}
|
||||
}
|
||||
6
day-18/internal/two/point.go
Normal file
6
day-18/internal/two/point.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package two
|
||||
|
||||
type point struct {
|
||||
x int
|
||||
y int
|
||||
}
|
||||
39
day-18/internal/two/solve.go
Normal file
39
day-18/internal/two/solve.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package two
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"github.com/onyx-and-iris/aoc2024/day-18/internal/config"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func Solve(buf []byte, config config.Config) (string, error) {
|
||||
r := bytes.NewReader(buf)
|
||||
graph, corruptedCoords, err := parseLines(r, config)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
log.Debugf("start: %v end: %v", graph.start, graph.end)
|
||||
|
||||
indx := runUntilNoPath(graph, corruptedCoords, config)
|
||||
return fmt.Sprintf("%d,%d", corruptedCoords[indx][0], corruptedCoords[indx][1]), nil
|
||||
}
|
||||
|
||||
func runUntilNoPath(graph *graph, corruptedCoords [][]int, config config.Config) int {
|
||||
for i, coords := range corruptedCoords[config.NumCorruptions+1:] {
|
||||
nextCorruption := point{coords[0], coords[1]}
|
||||
|
||||
log.Debugf("adding corruption %v", nextCorruption)
|
||||
|
||||
graph.addCorruption(coords)
|
||||
path, err := graph.dijkstra(graph.start, graph.end)
|
||||
if err != nil {
|
||||
log.Debug(err)
|
||||
return config.NumCorruptions + i + 1
|
||||
}
|
||||
log.Debugf("\n%s\n", graph.debug(path))
|
||||
}
|
||||
return 0
|
||||
}
|
||||
21
day-18/internal/two/solve_internal_test.go
Normal file
21
day-18/internal/two/solve_internal_test.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package two
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/onyx-and-iris/aoc2024/day-18/internal/config"
|
||||
)
|
||||
|
||||
//go:embed testdata/input.txt
|
||||
var data []byte
|
||||
|
||||
func BenchmarkSolve(b *testing.B) {
|
||||
os.Stdout, _ = os.Open(os.DevNull)
|
||||
Solve(data, config.Config{
|
||||
Width: 71,
|
||||
Height: 71,
|
||||
NumCorruptions: 1024,
|
||||
})
|
||||
}
|
||||
42
day-18/internal/two/util.go
Normal file
42
day-18/internal/two/util.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package two
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/onyx-and-iris/aoc2024/day-18/internal/config"
|
||||
)
|
||||
|
||||
func parseLines(r io.Reader, config config.Config) (*graph, [][]int, error) {
|
||||
corruptedCoords := [][]int{}
|
||||
scanner := bufio.NewScanner(r)
|
||||
for scanner.Scan() {
|
||||
corruptedCoords = append(corruptedCoords, func() []int {
|
||||
x := strings.Split(scanner.Text(), ",")
|
||||
return []int{mustConv(x[0]), mustConv(x[1])}
|
||||
}())
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
graph := newGraph(config.Width, config.Height, config.NumCorruptions, corruptedCoords)
|
||||
return graph, corruptedCoords, nil
|
||||
}
|
||||
|
||||
func mustConv(s string) int {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func replaceAtIndex(s string, r rune, i int) string {
|
||||
out := []rune(s)
|
||||
out[i] = r
|
||||
return string(out)
|
||||
}
|
||||
Reference in New Issue
Block a user