Compare commits

..

13 Commits

Author SHA1 Message Date
cacd140961 ^^ 2024-01-02 09:20:51 +00:00
0f357df19d Merge branch 'main' of https://github.com/onyx-and-iris/aoc2023 2024-01-02 09:19:19 +00:00
5b225a9166 adjust bound factory method to set open end of interval 2024-01-02 09:18:14 +00:00
9ba5ad695e add mutex lock 2024-01-02 06:58:03 +00:00
cc452c76a4 fix day-5 p2 2024-01-01 11:32:43 +00:00
73298dae8d move area calculation into a function
fix mustConvHex docstring
2023-12-24 10:50:41 +00:00
35776a5470 upd docstrings 2023-12-23 11:58:21 +00:00
2814b12750 rename var move for p2 2023-12-22 22:23:43 +00:00
e541631a35 rename var move in runner()
uncomment debug logs
2023-12-22 22:03:12 +00:00
038dd531d9 day-18 2023-12-22 21:57:00 +00:00
497da642b2 day-17 2023-12-22 21:56:07 +00:00
58f36581f0 upd makefiles 2023-12-18 19:12:56 +00:00
cb3506cfbc upd docstring 2023-12-17 20:49:11 +00:00
42 changed files with 781 additions and 199 deletions

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -25,7 +25,7 @@ func (i img) transposed() []string {
return transposed
}
// String implements the Stringer interface
// String implements the fmt.Stringer interface
func (i img) String() string {
out := ""
for _, line := range i.raw {

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -25,84 +25,82 @@ const (
var steps int
var dirs = []string{"N", "S", "W", "E"}
func runner(move *mover, lines []string) {
for steps < math.MaxInt && move.Y >= 0 && move.Y < len(lines) && move.X >= 0 && move.X < len(lines[move.Y]) {
//log.Debug(move.X, ":", move.Y, " ", string(lines[move.Y][move.X]), " ", dirs[move.direction()])
//log.Debug(move.nodes)
if nodeInNodes(move.node, move.nodes) {
log.Debug(move.node, " in nodes, breaking.")
func runner(mover *mover, lines []string) {
for steps < math.MaxInt && mover.Y >= 0 && mover.Y < len(lines) && mover.X >= 0 && mover.X < len(lines[mover.Y]) {
if nodeInNodes(mover.node, mover.nodes) {
log.Debug(mover.node, " in nodes, breaking.")
break
}
move.nodes = append(move.nodes, move.node)
mover.nodes = append(mover.nodes, mover.node)
switch lines[move.Y][move.X] {
switch lines[mover.Y][mover.X] {
case SPACE: // '.'
//log.Debug("we have space and direction is ", dirs[move.direction()])
move.move()
log.Debug("we have space and direction is ", dirs[mover.direction()])
mover.move()
case F_MIRROR: // '/'
//log.Debug("we have forward mirror and direction is ", dirs[move.direction()])
switch move.direction() {
log.Debug("we have forward mirror and direction is ", dirs[mover.direction()])
switch mover.direction() {
case N:
move.setDirection(E)
mover.setDirection(E)
case S:
move.setDirection(W)
mover.setDirection(W)
case W:
move.setDirection(S)
mover.setDirection(S)
case E:
move.setDirection(N)
mover.setDirection(N)
}
//log.Debug("step: ", steps, " ", string(F_MIRROR), " direction changed to ", dirs[move.direction()])
move.move()
log.Debug("step: ", steps, " ", string(F_MIRROR), " direction changed to ", dirs[mover.direction()])
mover.move()
case B_MIRROR: // '\'
//log.Debug("we have backwards mirror and direction is ", dirs[move.direction()])
switch move.direction() {
log.Debug("we have backwards mirror and direction is ", dirs[mover.direction()])
switch mover.direction() {
case N:
move.setDirection(W)
mover.setDirection(W)
case S:
move.setDirection(E)
mover.setDirection(E)
case W:
move.setDirection(N)
mover.setDirection(N)
case E:
move.setDirection(S)
mover.setDirection(S)
}
//log.Debug("step: ", steps, " ", string(B_MIRROR), " direction changed to ", dirs[move.direction()])
move.move()
log.Debug("step: ", steps, " ", string(B_MIRROR), " direction changed to ", dirs[mover.direction()])
mover.move()
case V_MIRROR: // '|'
//log.Debug("we have vertical mirror and direction is ", dirs[move.direction()])
if move.direction() == N || move.direction() == S {
move.move()
log.Debug("we have vertical mirror and direction is ", dirs[mover.direction()])
if mover.direction() == N || mover.direction() == S {
mover.move()
continue
}
if move.direction() == W || move.direction() == E {
c := move.coords
move.setDirection(N)
move.move()
runner(move, lines)
move.coords = c
move.setDirection(S)
move.move()
runner(move, lines)
if mover.direction() == W || mover.direction() == E {
c := mover.coords
mover.setDirection(N)
mover.move()
runner(mover, lines)
mover.coords = c
mover.setDirection(S)
mover.move()
runner(mover, lines)
}
case H_MIRROR: // '-'
//log.Debug("we have horizontal mirror and direction is ", dirs[move.direction()])
if move.direction() == W || move.direction() == E {
move.move()
log.Debug("we have horizontal mirror and direction is ", dirs[mover.direction()])
if mover.direction() == W || mover.direction() == E {
mover.move()
continue
}
if move.direction() == N || move.direction() == S {
c := move.coords
move.setDirection(W)
move.move()
runner(move, lines)
move.coords = c
move.setDirection(E)
move.move()
runner(move, lines)
if mover.direction() == N || mover.direction() == S {
c := mover.coords
mover.setDirection(W)
mover.move()
runner(mover, lines)
mover.coords = c
mover.setDirection(E)
mover.move()
runner(mover, lines)
}
default:
@@ -114,14 +112,14 @@ func runner(move *mover, lines []string) {
// one
func one(lines []string) int {
move := newMover(newNode(0, 0, E))
mover := newMover(newNode(0, 0, E))
runner(move, lines)
runner(mover, lines)
if log.GetLevel() == log.DebugLevel {
n := printDebug(move, lines)
n := printDebug(mover, lines)
log.Debug("total: ", n)
}
return uniqueNodes(move)
return uniqueNodes(mover)
}

View File

@@ -3,9 +3,9 @@ package main
import "sync"
// returns the number of unique nodes (reducing multiple nodes with different directions to one)
func uniqueNodes(move *mover) int {
func uniqueNodes(mover *mover) int {
uniqueCoords := []coords{}
for _, node := range move.nodes {
for _, node := range mover.nodes {
if !coordInCoords(node.coords, uniqueCoords) {
uniqueCoords = append(uniqueCoords, node.coords)
}

3
day-17/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module github.com/onyx-and-iris/aoc2023/day-17
go 1.21.5

10
day-17/makefile Normal file
View File

@@ -0,0 +1,10 @@
TEST="test.txt"
INPUT="input.txt"
test:
go run . < $(TEST)
run:
go run . < $(INPUT)
all: test

32
day-17/node.go Normal file
View File

@@ -0,0 +1,32 @@
package main
import "fmt"
type coords struct {
X int
Y int
}
func newCoords(x, y int) coords {
return coords{X: x, Y: y}
}
// node represents a single point on the graph
type node struct {
cost int
distance int
directionX int
directionY int
coords
index int
}
func newNode(cost, distance, directionX, directionY, x, y int) *node {
c := newCoords(x, y)
return &node{cost: cost, distance: distance, directionX: directionX, directionY: directionY, coords: c}
}
// String implements the fmt.Stringer interface
func (n node) String() string {
return fmt.Sprintf("%d%d%d%v", n.distance, n.directionX, n.directionY, n.coords)
}

114
day-17/one.go Normal file
View File

@@ -0,0 +1,114 @@
package main
import (
"container/heap"
log "github.com/sirupsen/logrus"
)
type option func(*dijkstra)
func WithMinDistance(distance int) option {
return func(d *dijkstra) {
d.minDistance = distance
}
}
func WithMaxDistance(distance int) option {
return func(d *dijkstra) {
d.maxDistance = distance
}
}
type dijkstra struct {
graph [][]int
minDistance int
maxDistance int
}
func newDijkstra(graph [][]int, opts ...option) *dijkstra {
d := &dijkstra{graph: graph}
for _, opt := range opts {
opt(d)
}
return d
}
func (d dijkstra) initialize(start coords) *pqueue {
pq := newPriorityQueue()
heap.Init(pq)
// we don't encounter heat loss for start point unless we enter this block again
heap.Push(pq, newNode(0, 0, 0, 0, start.X, start.Y))
return pq
}
// run performs the lowest cost dijkstra algorithm from start to end
func (d dijkstra) run(start, end coords) int {
pq := d.initialize(start)
visited := map[string]bool{}
for pq.Len() > 0 {
cost, node := func() (int, *node) {
x := heap.Pop(pq).(*node)
return x.cost, x
}()
// we reached final location, return its lowest cost
if node.X == end.X && node.Y == end.Y && node.distance >= d.minDistance {
log.Debug("returning lowest cost with min distance >= ", d.minDistance)
return node.cost
}
if _, ok := visited[node.String()]; ok {
continue
}
visited[node.String()] = true
var neighbours = [][]int{{0, -1}, {0, 1}, {-1, 0}, {1, 0}} // N, S, W, E
for _, n := range neighbours {
nextX := node.X + n[0]
nextY := node.Y + n[1]
if nextY < 0 || nextY >= len(d.graph) || nextX < 0 || nextX >= len(d.graph[nextY]) {
continue
}
if node.directionX == -n[0] && node.directionY == -n[1] { // are we going backwards?
continue
}
var distance = 1
if node.directionX == n[0] || node.directionY == n[1] { // same direction
distance = node.distance + 1
} else {
if node.distance < d.minDistance {
continue
}
}
if distance > d.maxDistance {
continue
}
new_cost := cost + d.graph[nextY][nextX]
heap.Push(pq, newNode(new_cost, distance, n[0], n[1], nextX, nextY))
}
}
return 0
}
// one returns the lowest cost path for the given graph from start to end coords
func one(lines []string) int {
graph := buildGraph(lines)
start := newCoords(0, 0)
end := newCoords(len(graph[0])-1, len(graph)-1)
dijkstra := newDijkstra(graph, WithMaxDistance(3))
cost := dijkstra.run(start, end)
return cost
}

49
day-17/pqueue.go Normal file
View File

@@ -0,0 +1,49 @@
package main
import (
"container/heap"
)
// pqueue represents a min priority queue
// it implements the heap.Interface interface
type pqueue []*node
func newPriorityQueue() *pqueue {
pq := make(pqueue, 0)
return &pq
}
func (pq pqueue) Len() int {
return len(pq)
}
func (pq *pqueue) Push(x interface{}) {
n := len(*pq)
node := x.(*node)
node.index = n
*pq = append(*pq, node)
}
func (pq *pqueue) Pop() interface{} {
old := *pq
n := len(old)
node := old[n-1]
node.index = -1
*pq = old[0 : n-1]
return node
}
func (pq *pqueue) Update(node *node, value int) {
node.cost = value
heap.Fix(pq, node.index)
}
func (pq pqueue) Less(i, j int) bool {
return pq[i].cost < pq[j].cost
}
func (pq pqueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}

27
day-17/pqueue_test.go Normal file
View File

@@ -0,0 +1,27 @@
package main
import (
"container/heap"
"testing"
"github.com/go-playground/assert/v2"
)
func TestPriorityQueue(t *testing.T) {
//t.Skip("skipping test")
pq := newPriorityQueue()
heap.Push(pq, newNode(30, 0, 0, 0, 0, 0))
heap.Push(pq, newNode(10, 0, 0, 0, 8, 0))
heap.Push(pq, newNode(20, 0, 0, 0, 13, 0))
t.Run("Should create a queue size 3", func(t *testing.T) {
assert.Equal(t, 3, pq.Len())
})
item := heap.Pop(pq).(*node)
t.Run("Should return item with cost 10", func(t *testing.T) {
assert.Equal(t, 10, item.cost)
})
}

21
day-17/solution.go Normal file
View File

@@ -0,0 +1,21 @@
package main
import (
"fmt"
log "github.com/sirupsen/logrus"
)
func init() {
log.SetLevel(log.InfoLevel)
}
func main() {
lines := readlines()
ans := one(lines)
fmt.Printf("solution one: %d\n", ans)
ans = two(lines)
fmt.Printf("solution two: %d\n", ans)
}

14
day-17/two.go Normal file
View File

@@ -0,0 +1,14 @@
package main
// two returns the lowest cost path for a given graph from start to end coords
// with a min/max distance set
func two(lines []string) int {
graph := buildGraph(lines)
start := newCoords(0, 0)
end := newCoords(len(graph[0])-1, len(graph)-1)
dijkstra := newDijkstra(graph, WithMinDistance(4), WithMaxDistance(10))
cost := dijkstra.run(start, end)
return cost
}

26
day-17/two_test.go Normal file
View File

@@ -0,0 +1,26 @@
package main
import (
_ "embed"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
var (
//go:embed test2.txt
testInput2 []byte
)
func TestDjistraWithMinDistance(t *testing.T) {
//t.Skip("skipping test")
input := strings.Split(string(testInput2), "\n")
cost := two(input)
t.Run("Should return a lowest cost of 71", func(t *testing.T) {
assert.Equal(t, 71, cost)
})
}

38
day-17/util.go Normal file
View File

@@ -0,0 +1,38 @@
package main
import (
"bufio"
"log"
"os"
)
// readlines reads lines from stdin.
// it returns them as an array of strings
func readlines() []string {
lines := []string{}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return lines
}
// buildGraph parses lines into costs for graph
func buildGraph(lines []string) [][]int {
graph := make([][]int, len(lines))
for i, line := range lines {
graph[i] = make([]int, len(line))
for j, r := range line {
graph[i][j] = int(r - '0')
}
}
return graph
}

3
day-18/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module github.com/onyx-and-iris/aoc2023/day-18
go 1.21.5

37
day-18/imager.go Normal file
View File

@@ -0,0 +1,37 @@
package main
type coords struct {
X int
Y int
}
func newCoords(x, y int) coords {
return coords{X: x, Y: y}
}
type imager struct {
point coords
space []coords
}
// newImager returns an imager type
func newImager() *imager {
return &imager{point: newCoords(0, 0), space: make([]coords, 0)}
}
// add appends new coordinates to all points that describe the polygon
func (i *imager) add(direction string, count int) {
for j := 0; j < count; j++ {
switch direction {
case "U":
i.point.Y--
case "D":
i.point.Y++
case "L":
i.point.X--
case "R":
i.point.X++
}
i.space = append(i.space, newCoords(i.point.X, i.point.Y))
}
}

10
day-18/makefile Normal file
View File

@@ -0,0 +1,10 @@
TEST="test.txt"
INPUT="input.txt"
test:
go run . < $(TEST)
run:
go run . < $(INPUT)
all: test

29
day-18/one.go Normal file
View File

@@ -0,0 +1,29 @@
package main
import (
"regexp"
)
var r = regexp.MustCompile(`(?P<direction>[A-Z]) (?P<count>[0-9]+) \((?P<colour>.*)\)`)
func fromRegex(imager *imager, lines []string) {
for _, line := range lines {
direction, count := func() (string, int) {
x := getParams(r, line)
return x["direction"], mustConv(x["count"])
}()
imager.add(direction, count)
}
}
func buildImage(withParser func(imager *imager, lines []string), imager *imager, lines []string) {
withParser(imager, lines)
}
// one returns the area of the polygon described by imager.space
func one(lines []string) int {
imager := newImager()
buildImage(fromRegex, imager, lines)
return calculateArea(imager.space)
}

22
day-18/solution.go Normal file
View File

@@ -0,0 +1,22 @@
package main
import (
"fmt"
log "github.com/sirupsen/logrus"
)
func init() {
log.SetLevel(log.InfoLevel)
}
func main() {
lines := readlines()
ans := one(lines)
fmt.Printf("solution one: %d\n", ans)
ans = two(lines)
fmt.Printf("solution two: %d\n", ans)
}

26
day-18/two.go Normal file
View File

@@ -0,0 +1,26 @@
package main
import (
"strings"
)
func fromHex(imager *imager, lines []string) {
for _, line := range lines {
direction, count := func() (string, int) {
var dirs = []string{"R", "D", "L", "U"}
m := getParams(r, line)
code := strings.TrimLeft(m["colour"], "#")
return dirs[mustConv(string(code[len(code)-1]))], mustConvHex(code[:len(code)-1])
}()
imager.add(direction, count)
}
}
// two returns the area of the polygon described by imager.space
// it uses the hex codes to define points
func two(lines []string) int {
imager := newImager()
buildImage(fromHex, imager, lines)
return calculateArea(imager.space)
}

73
day-18/util.go Normal file
View File

@@ -0,0 +1,73 @@
package main
import (
"bufio"
"log"
"math"
"os"
"regexp"
"strconv"
)
// readlines reads lines from stdin.
// it returns them as an array of strings
func readlines() []string {
lines := []string{}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return lines
}
func getParams(rexp *regexp.Regexp, url string) map[string]string {
match := rexp.FindStringSubmatch(url)
m := make(map[string]string)
for i, name := range rexp.SubexpNames() {
if i > 0 && i <= len(match) {
m[name] = match[i]
}
}
return m
}
// mustConv converts string to int
// it will panic if an error occurs
func mustConv(s string) int {
n, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return n
}
// mustConvHex converts a hex string to int
// it will panic if an error occurs
func mustConvHex(s string) int {
n, err := strconv.ParseInt(s, 16, 64)
if err != nil {
panic(err)
}
return int(n)
}
// calculateArea returns the area of the polygon described by imager.space
func calculateArea(space []coords) int {
area := 0
for i := 0; i < len(space); i++ {
next := space[(i+1)%len(space)]
area += space[i].X*next.Y - space[i].Y*next.X
}
// add perimeter to area within perimeter
area = len(space) + (int(math.Abs(float64(area))) / 2)
return area - len(space)/2 + 1
}

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -1,19 +1,22 @@
package main
type Data struct {
type data struct {
dest int
source int
offset int
}
var seeds = []int{}
var dataMap = map[string][]Data{
"seed-to-soil": make([]Data, 0),
"soil-to-fertilizer": make([]Data, 0),
"fertilizer-to-water": make([]Data, 0),
"water-to-light": make([]Data, 0),
"light-to-temperature": make([]Data, 0),
"temperature-to-humidity": make([]Data, 0),
"humidity-to-location": make([]Data, 0),
func newData(nums ...int) data {
return data{dest: nums[0], source: nums[1], offset: nums[2]}
}
func (d data) transform(start, end int) (int, int) {
f := func(x int) int {
return x - d.source + d.dest
}
return f(start), f(end - 1)
}
var dataMap = map[string][]data{}
var identifiers = []string{}

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,43 +2,36 @@ package main
import (
"math"
log "github.com/sirupsen/logrus"
)
var identifiers = []string{"seed-to-soil", "soil-to-fertilizer", "fertilizer-to-water", "water-to-light", "light-to-temperature", "temperature-to-humidity", "humidity-to-location"}
var seeds = []int{}
// next recursively calculates each destination for each set of data in dataMap
func next(i int, datapoint int) int {
if i == len(identifiers) {
return datapoint
}
dest := func() int {
datas := dataMap[identifiers[i]]
dest := 0
for _, data := range datas {
if datapoint >= data.source && datapoint <= data.source+data.offset {
dest = data.dest + (datapoint - data.source)
break
}
dest := 0
for _, data := range dataMap[identifiers[i]] {
if datapoint >= data.source && datapoint <= data.source+data.offset {
dest = data.dest + (datapoint - data.source)
break
}
if dest == 0 {
dest = datapoint
}
return dest
}()
//log.Debug(identifiers[i], ": ", dest)
}
if dest == 0 {
dest = datapoint
}
return next(i+1, dest)
}
// one returns the lowest location
// one returns the lowest location for any seed in seeds
func one(lines []string) (int, error) {
lowest := math.MaxInt
parseLines(lines)
lowest := math.MaxInt
for _, seed := range seeds {
location := next(0, seed)
log.Info(location)
if location < lowest {
lowest = location
}

51
day-5/queue.go Normal file
View File

@@ -0,0 +1,51 @@
package main
import (
log "github.com/sirupsen/logrus"
)
// queue represents a FIFO queue of bounds
type queue struct {
size int
elements []bound
}
// newQueue returns a queue type
// it initializes the queue size and elements
func newQueue(size int, elems []bound) queue {
return queue{size: size, elements: elems}
}
// enqueue adds an item to the queue
func (q *queue) enqueue(elem bound) {
if q.size >= 0 && q.getLength() == q.size {
log.Info("Queue Overflow")
return
}
q.elements = append(q.elements, elem)
}
// dequeue pops an element from the start of the queue
func (q *queue) dequeue() bound {
if q.isEmpty() {
log.Info("Queue UnderFlow")
return bound{}
}
element := q.elements[0]
if q.getLength() == 1 {
q.elements = nil
return element
}
q.elements = q.elements[1:]
return element
}
// getLength returns the number of items in the queue
func (q *queue) getLength() int {
return len(q.elements)
}
// isEmpty returns true if no items are in the queue
func (q *queue) isEmpty() bool {
return len(q.elements) == 0
}

View File

@@ -7,7 +7,7 @@ import (
)
func init() {
log.SetLevel(log.DebugLevel)
log.SetLevel(log.InfoLevel)
}
func main() {
@@ -19,9 +19,6 @@ func main() {
}
fmt.Printf("solution one: %d\n", ans)
ans, err = two(lines)
if err != nil {
log.Fatal(err)
}
ans = two(lines)
fmt.Printf("solution two: %d\n", ans)
}

View File

@@ -1,78 +1,89 @@
package main
import (
"fmt"
"math"
"sync"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
)
type WaitGroupCount struct {
sync.WaitGroup
count int64
}
var wg sync.WaitGroup
var mu sync.Mutex
func (wg *WaitGroupCount) Add(delta int) {
atomic.AddInt64(&wg.count, int64(delta))
wg.WaitGroup.Add(delta)
}
func (wg *WaitGroupCount) Done() {
atomic.AddInt64(&wg.count, -1)
wg.WaitGroup.Done()
}
func (wg *WaitGroupCount) GetCount() int {
return int(atomic.LoadInt64(&wg.count))
}
var wg = WaitGroupCount{}
//var checked = make([]bound, 0)
const UNLIMITED = -1
// bound represents the lower and upper limits of a single range
type bound struct {
start int
end int
lower, upper int
}
var bounds = []bound{}
// newBound returns a bound type
// it defines an open ended interval
func newBound(lower, upper int) bound {
return bound{lower: lower, upper: upper - 1}
}
// two returns the lowest location
func two(lines []string) (int, error) {
lowest := math.MaxInt
for i := 0; i < len(seeds); i += 2 {
bounds = append(bounds, bound{start: seeds[i], end: seeds[i] + seeds[i+1]})
// nextTransform recursively calculates each new set of seed ranges for each set of data in dataMap
func nextTransform(i int, in []bound) []bound {
if i == len(identifiers) {
return in
}
startTime := time.Now()
q := newQueue(UNLIMITED, in)
in = make([]bound, 0)
for !q.isEmpty() {
r := q.dequeue()
go func() {
for {
elapsed := time.Since(startTime)
fmt.Printf("[%s] wg count: %d\n", elapsed.Round(time.Second), wg.GetCount())
time.Sleep(time.Second)
}
}()
hasOverlap := func() bool {
for _, data := range dataMap[identifiers[i]] {
start := max(r.lower, data.source)
end := min(r.upper, data.source+data.offset)
for _, bound := range bounds {
wg.Add(1)
go func(start int, end int) {
defer wg.Done()
for i := start; i < end; i++ {
location := next(0, i)
if location < lowest {
lowest = location
if isOverlapping(start, end) {
// add new seed range
in = append(in, newBound(data.transform(start, end)))
// append unmatched portions of seed range back into queue
if start > r.lower {
q.enqueue(newBound(r.lower, start))
}
if r.upper > end {
q.enqueue(newBound(end, r.upper))
}
return true
}
}
}(bound.start, bound.end)
log.Info(bound, " completed")
return false
}()
// there was no overlap, add the seed range as is
if !hasOverlap {
in = append(in, r)
}
}
return nextTransform(i+1, in)
}
// two returns the lowest location for any seed in seedRanges
func two(lines []string) int {
var seedRanges = []bound{}
for i := 0; i < len(seeds); i += 2 {
wg.Add(1)
go func(i int) {
defer wg.Done()
mu.Lock()
seedRanges = append(seedRanges, nextTransform(0, []bound{newBound(seeds[i], seeds[i]+seeds[i+1])})...)
mu.Unlock()
}(i)
}
wg.Wait()
return lowest - 1, nil // returning a value one too high? not sure why.
lowest := math.MaxInt
for _, r := range seedRanges {
if r.lower < lowest {
lowest = r.lower
}
}
return lowest
}

View File

@@ -2,12 +2,13 @@ package main
import (
"bufio"
"log"
"os"
"regexp"
"strconv"
"strings"
"unicode"
log "github.com/sirupsen/logrus"
)
// readlines reads lines from stdin.
@@ -27,28 +28,27 @@ func readlines() []string {
return lines
}
var r = regexp.MustCompile(`([\w-]+) map[:]`)
// parseLines parses input to a data map
func parseLines(lines []string) {
var _regex_identifier = regexp.MustCompile(`(?P<identifier>[\w-]+) map[:]`)
f := func(c rune) bool {
return !unicode.IsDigit(c)
}
for i := 0; i < len(lines); i++ {
if i == 0 {
seeds = convertToInts(strings.FieldsFunc(lines[i], f))
continue
}
seeds = convertToInts(strings.FieldsFunc(lines[0], f))
m := _regex_identifier.FindStringSubmatch(lines[i])
for i := 2; i < len(lines); i++ {
m := r.FindStringSubmatch(lines[i])
if len(m) == 2 {
identifiers = append(identifiers, m[1])
for i = i + 1; i < len(lines) && len(lines[i]) != 0; i++ {
nums := convertToInts(strings.FieldsFunc(lines[i], f))
dataMap[m[1]] = append(dataMap[m[1]], Data{dest: nums[0], source: nums[1], offset: nums[2]})
d := newData(convertToInts(strings.FieldsFunc(lines[i], f))...)
dataMap[m[1]] = append(dataMap[m[1]], d)
}
}
}
log.Debug(identifiers)
}
// convertToInts converts a string representing ints to an array of ints
@@ -61,13 +61,8 @@ func convertToInts(data []string) []int {
return nums
}
/*
func isChecked(i int) bool {
for _, bound := range checked {
if i > bound.start && i < bound.end {
return true
}
}
return false
// isOverlapping returns true if two ranges overlap. see:
// https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap/325964#325964
func isOverlapping(maxStart, minEnd int) bool {
return maxStart < minEnd
}
*/

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test

View File

@@ -2,9 +2,9 @@ TEST="test.txt"
INPUT="input.txt"
test:
cat $(TEST) | go run .
go run . < $(TEST)
run:
cat $(INPUT) | go run .
go run . < $(INPUT)
all: test