add day-14 + benchmarks

This commit is contained in:
onyx-and-iris 2024-12-14 19:11:58 +00:00
parent 7b17f8edc1
commit d441f6a555
20 changed files with 578 additions and 0 deletions

15
day-14/benchmark Normal file
View File

@ -0,0 +1,15 @@
goos: linux
goarch: amd64
pkg: github.com/onyx-and-iris/aoc2024/day-14
cpu: Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
BenchmarkSolve-12 1000000000 0.4641 ns/op
BenchmarkSolve-12 1000000000 0.5193 ns/op
BenchmarkSolve-12 1000000000 0.5324 ns/op
BenchmarkSolve-12 1000000000 0.4540 ns/op
BenchmarkSolve-12 1000000000 0.4623 ns/op
BenchmarkSolve-12 1000000000 0.4455 ns/op
BenchmarkSolve-12 1000000000 0.4577 ns/op
BenchmarkSolve-12 1000000000 0.4646 ns/op
BenchmarkSolve-12 1000000000 0.4496 ns/op
BenchmarkSolve-12 1000000000 0.4566 ns/op
ok github.com/onyx-and-iris/aoc2024/day-14 114.332s

41
day-14/cmd/cli/main.go Normal file
View File

@ -0,0 +1,41 @@
/********************************************************************************
Advent of Code 2024 - day-14
********************************************************************************/
package main
import (
"embed"
"flag"
"fmt"
"slices"
log "github.com/sirupsen/logrus"
problems "github.com/onyx-and-iris/aoc2024/day-14"
)
//go:embed testdata
var files embed.FS
func main() {
filename := flag.String("f", "input.txt", "input file")
loglevel := flag.Int("l", int(log.InfoLevel), "log level")
flag.Parse()
if slices.Contains(log.AllLevels, log.Level(*loglevel)) {
log.SetLevel(log.Level(*loglevel))
}
data, err := files.ReadFile(fmt.Sprintf("testdata/%s", *filename))
if err != nil {
log.Fatal(err)
}
one, two, err := problems.Solve(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("solution one: %d\nsolution two: %d\n", one, two)
}

7
day-14/go.mod Normal file
View File

@ -0,0 +1,7 @@
module github.com/onyx-and-iris/aoc2024/day-14
go 1.23.3
require github.com/sirupsen/logrus v1.9.3
require golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect

15
day-14/go.sum Normal file
View File

@ -0,0 +1,15 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -0,0 +1,6 @@
goos: linux
goarch: amd64
pkg: github.com/onyx-and-iris/aoc2024/day-14/internal/one
cpu: Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
BenchmarkSolve-12 1000000000 0.0007711 ns/op
ok github.com/onyx-and-iris/aoc2024/day-14/internal/one 0.011s

View File

@ -0,0 +1,36 @@
package one
type dimension int
type graph struct {
data [][]int
}
func newGraph(x, y dimension) *graph {
var data [][]int
for range y {
data = append(data, make([]int, x))
}
return &graph{data: data}
}
func (g *graph) update(robots []*robot) {
for _, robot := range robots {
g.updateEach(robot.position)
}
}
func (g *graph) updateEach(p position) {
g.data[p.y][p.x]++
}
func (g *graph) quadrant(startx, endx, starty, endy int) int {
var robotCount int
for i := starty; i < endy; i++ {
for j := startx; j < endx; j++ {
robotCount += g.data[i][j]
}
}
return robotCount
}

View File

@ -0,0 +1,51 @@
package one
import (
"fmt"
)
type position struct {
x int
y int
}
type velocity struct {
x int
y int
}
type robot struct {
position position
velocity velocity
}
func newRobot(px, py, vx, vy int) *robot {
return &robot{
position{x: px, y: py},
velocity{x: vx, y: vy},
}
}
func (r *robot) String() string {
return fmt.Sprintf("position: %+v velocity: %+v", r.position, r.velocity)
}
func (r *robot) update(width, height dimension) position {
oldPosition := r.position
r.position.x += r.velocity.x
if r.position.x < 0 {
r.position.x = int(width) + r.position.x
} else if r.position.x >= int(width) {
r.position.x = r.position.x - int(width)
}
r.position.y += r.velocity.y
if r.position.y < 0 {
r.position.y = int(height) + r.position.y
} else if r.position.y >= int(height) {
r.position.y = r.position.y - int(height)
}
return oldPosition
}

View File

@ -0,0 +1,41 @@
package one
import (
"bytes"
)
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
robots, err := parseLines(r)
if err != nil {
return 0, err
}
const numSeconds int = 100
const width, height dimension = 101, 103
graph := newGraph(width, height)
for range numSeconds {
for _, robot := range robots {
robot.update(width, height)
}
}
graph.update(robots)
safetyFactor := 1
for _, v := range calculateQuadrants(graph) {
safetyFactor *= v
}
return safetyFactor, nil
}
func calculateQuadrants(graph *graph) []int {
topLeft := graph.quadrant(0, len(graph.data[0])/2, 0, len(graph.data)/2)
topRight := graph.quadrant(len(graph.data[0])/2+1, len(graph.data[0]), 0, len(graph.data)/2)
bottomLeft := graph.quadrant(0, len(graph.data[0])/2, len(graph.data)/2+1, len(graph.data))
bottomRight := graph.quadrant(len(graph.data[0])/2+1, len(graph.data[0]), len(graph.data)/2+1, len(graph.data))
return []int{topLeft, topRight, bottomLeft, bottomRight}
}

View File

@ -0,0 +1,15 @@
package one
import (
_ "embed"
"os"
"testing"
)
//go:embed testdata/input.txt
var data []byte
func BenchmarkSolve(b *testing.B) {
os.Stdout, _ = os.Open(os.DevNull)
Solve(data)
}

View File

@ -0,0 +1,40 @@
package one
import (
"bufio"
"io"
"regexp"
"strconv"
)
var reRobot = regexp.MustCompile(`p=(?P<px>\d+),(?P<py>\d+) v=(?P<vx>-?\d+),(?P<vy>-?\d+)`)
func parseLines(r io.Reader) ([]*robot, error) {
var matches [][]string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
m := reRobot.FindStringSubmatch(line)
matches = append(matches, m)
}
if err := scanner.Err(); err != nil {
return nil, err
}
var robots []*robot
for _, m := range matches {
robots = append(robots, newRobot(mustConv(m[1]), mustConv(m[2]), mustConv(m[3]), mustConv(m[4])))
}
return robots, nil
}
func mustConv(s string) int {
n, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return n
}

View File

@ -0,0 +1,6 @@
goos: linux
goarch: amd64
pkg: github.com/onyx-and-iris/aoc2024/day-14/internal/two
cpu: Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
BenchmarkSolve-12 1000000000 0.4504 ns/op
ok github.com/onyx-and-iris/aoc2024/day-14/internal/two 11.186s

View File

@ -0,0 +1,59 @@
package two
import (
"strings"
)
type dimension int
type graph struct {
x dimension
y dimension
data [][]int
}
func newGraph(x, y dimension) *graph {
var data [][]int
for range y {
data = append(data, make([]int, x))
}
return &graph{x: x, y: y, data: data}
}
func (g *graph) String() string {
temp := []string{}
for range len(g.data) {
temp = append(temp, string(make([]byte, len(g.data[0]))))
}
for i := 0; i < len(g.data); i++ {
for j := 0; j < len(g.data[0]); j++ {
if g.data[i][j] == 0 {
temp[i] = replaceAtIndex(temp[i], '.', j)
} else {
temp[i] = replaceAtIndex(temp[i], '*', j)
}
}
}
return strings.Join(temp, "\n")
}
func (g *graph) update(robots []*robot) {
for _, robot := range robots {
g.updateEach(robot.position)
}
}
func (g *graph) updateEach(p position) {
g.data[p.y][p.x]++
}
func (g *graph) isOutOfBounds(p position) 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 position) int {
return g.data[p.y][p.x]
}

View File

@ -0,0 +1,14 @@
package two
func neighbours(p position) [8]position {
return [8]position{
{p.x, p.y - 1}, // N
{p.x + 1, p.y - 1}, // NE
{p.x + 1, p.y}, // E
{p.x + 1, p.y + 1}, // SE
{p.x, p.y + 1}, // S
{p.x - 1, p.y + 1}, // Sw
{p.x - 1, p.y}, // W
{p.x - 1, p.y - 1}, // NW
}
}

View File

@ -0,0 +1,51 @@
package two
import (
"fmt"
)
type position struct {
x int
y int
}
type velocity struct {
x int
y int
}
type robot struct {
position position
velocity velocity
}
func newRobot(px, py, vx, vy int) *robot {
return &robot{
position{x: px, y: py},
velocity{x: vx, y: vy},
}
}
func (r *robot) String() string {
return fmt.Sprintf("position: %+v velocity: %+v", r.position, r.velocity)
}
func (r *robot) update(width, height dimension) position {
oldPosition := r.position
r.position.x += r.velocity.x
if r.position.x < 0 {
r.position.x = int(width) + r.position.x
} else if r.position.x >= int(width) {
r.position.x = r.position.x - int(width)
}
r.position.y += r.velocity.y
if r.position.y < 0 {
r.position.y = int(height) + r.position.y
} else if r.position.y >= int(height) {
r.position.y = r.position.y - int(height)
}
return oldPosition
}

View File

@ -0,0 +1,55 @@
package two
import (
"bytes"
log "github.com/sirupsen/logrus"
)
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
robots, err := parseLines(r)
if err != nil {
return 0, err
}
const maxSeconds int = 10e3
const width, height dimension = 101, 103
var graph *graph
var max, maxAtSecond int
for i := 1; i <= maxSeconds; i++ {
graph = newGraph(width, height)
for _, robot := range robots {
robot.update(width, height)
}
graph.update(robots)
numNeighbours := evaluateNeighbours(graph, robots)
if numNeighbours > max {
max = numNeighbours
maxAtSecond = i
}
}
log.Debugf("\n%s\n", graph.String())
return maxAtSecond, nil
}
func evaluateNeighbours(graph *graph, robots []*robot) int {
var numNeighbours int
for _, robot := range robots {
for _, n := range neighbours(robot.position) {
if graph.isOutOfBounds(n) {
continue
}
if graph.valueAt(n) > 0 {
numNeighbours++
}
}
}
return numNeighbours
}

View File

@ -0,0 +1,15 @@
package two
import (
_ "embed"
"os"
"testing"
)
//go:embed testdata/input.txt
var data []byte
func BenchmarkSolve(b *testing.B) {
os.Stdout, _ = os.Open(os.DevNull)
Solve(data)
}

View File

@ -0,0 +1,46 @@
package two
import (
"bufio"
"io"
"regexp"
"strconv"
)
var reRobot = regexp.MustCompile(`p=(?P<px>\d+),(?P<py>\d+) v=(?P<vx>-?\d+),(?P<vy>-?\d+)`)
func parseLines(r io.Reader) ([]*robot, error) {
var matches [][]string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
m := reRobot.FindStringSubmatch(line)
matches = append(matches, m)
}
if err := scanner.Err(); err != nil {
return nil, err
}
var robots []*robot
for _, m := range matches {
robots = append(robots, newRobot(mustConv(m[1]), mustConv(m[2]), mustConv(m[3]), mustConv(m[4])))
}
return robots, 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)
}

30
day-14/makefile Normal file
View File

@ -0,0 +1,30 @@
program = day-14
GO = go
SRC_DIR := src
BIN_DIR := bin
EXE := $(BIN_DIR)/$(program)
.DEFAULT_GOAL := build
.PHONY: fmt vet build bench clean
fmt:
$(GO) fmt ./...
vet: fmt
$(GO) vet ./...
build: vet | $(BIN_DIR)
$(GO) build -o $(EXE) ./$(SRC_DIR)
bench:
$(GO) test ./internal/one/ -bench=. > internal/one/benchmark
$(GO) test ./internal/two/ -bench=. > internal/two/benchmark
$(GO) test . -count=10 -bench=. > benchmark
$(BIN_DIR):
@mkdir -p $@
clean:
@rm -rv $(BIN_DIR)

20
day-14/solve.go Normal file
View File

@ -0,0 +1,20 @@
package dayfourteen
import (
"github.com/onyx-and-iris/aoc2024/day-14/internal/one"
"github.com/onyx-and-iris/aoc2024/day-14/internal/two"
)
func Solve(buf []byte) (int, int, error) {
answerOne, err := one.Solve(buf)
if err != nil {
return 0, 0, err
}
answerTwo, err := two.Solve(buf)
if err != nil {
return 0, 0, err
}
return answerOne, answerTwo, nil
}

View File

@ -0,0 +1,15 @@
package dayfourteen
import (
_ "embed"
"os"
"testing"
)
//go:embed testdata/input.txt
var data []byte
func BenchmarkSolve(b *testing.B) {
os.Stdout, _ = os.Open(os.DevNull)
Solve(data)
}