2021 day 13,15,16. need to clean up this code quite a bit

This commit is contained in:
alexchao26
2021-12-18 12:22:42 -05:00
parent d9f24da95a
commit 84647b8a94
6 changed files with 796 additions and 0 deletions
+149
View File
@@ -0,0 +1,149 @@
package main
import (
_ "embed"
"flag"
"fmt"
"regexp"
"strings"
"github.com/alexchao26/advent-of-code-go/cast"
"github.com/alexchao26/advent-of-code-go/util"
)
//go:embed input.txt
var input string
func init() {
// do this in init (not main) so test file has same input
input = strings.TrimRight(input, "\n")
if len(input) == 0 {
panic("empty input.txt file")
}
}
func main() {
var part int
flag.IntVar(&part, "part", 1, "part 1 or 2")
flag.Parse()
fmt.Println("Running part", part)
if part == 1 {
ans := part1(input)
util.CopyToClipboard(fmt.Sprintf("%v", ans))
fmt.Println("Output:", ans)
} else {
ans := part2(input)
util.CopyToClipboard(fmt.Sprintf("%v", ans))
fmt.Println("Output:", ans)
}
}
func part1(input string) int {
parts := strings.Split(input, "\n\n")
coords := map[[2]int]bool{}
// parse coords
for _, line := range strings.Split(parts[0], "\n") {
sp := strings.Split(line, ",")
coords[[2]int{cast.ToInt(sp[0]), cast.ToInt(sp[1])}] = true
}
fmt.Println(len(coords))
// // printing is a pita
// grid := make([][]int, 15)
// for i := range grid {
// grid[i] = make([]int, 15)
// }
// for c := range coords {
// grid[c[1]][c[0]] = 1
// }
// for _, row := range grid {
// fmt.Println(row)
// }
for _, fold := range strings.Split(parts[1], "\n") {
cap := regexp.MustCompile(`fold along (x|y)=(\d+)`).FindStringSubmatch(fold)
// remove full match
cap = cap[1:]
dir := cap[0]
foldCoord := cast.ToInt(cap[1])
fmt.Println("folding on", dir, foldCoord)
// fmt.Println(fold, dir, line)
// dots will never appear exactly on a fold line
isFoldOnX := dir == "x"
nextMap := map[[2]int]bool{}
if isFoldOnX {
for c := range coords {
if c[0] > foldCoord {
folded := [2]int{
foldCoord - (c[0] - foldCoord),
c[1],
}
fmt.Println(c, "to", folded)
nextMap[folded] = true
} else {
nextMap[c] = true
}
}
} else {
// fold on y
for c := range coords {
if c[1] > foldCoord {
folded := [2]int{
c[0],
foldCoord - (c[1] - foldCoord),
}
fmt.Println(c, "to", folded)
nextMap[folded] = true
} else {
nextMap[c] = true
}
}
}
coords = nextMap
// TODO just break for part 1
// break
}
// printing is a pita
max := 0
for c := range coords {
if c[0] > max {
max = c[0]
}
if c[1] > max {
max = c[1]
}
}
grid := make([][]int, max+1)
for i := range grid {
grid[i] = make([]int, max+1)
}
for c := range coords {
grid[c[1]][c[0]] = 1
}
for _, row := range grid {
str := ""
for _, val := range row {
if val == 1 {
str += "#"
} else {
str += "."
}
}
fmt.Println(str)
}
return len(coords)
}
func part2(input string) int {
return 0
}
+79
View File
@@ -0,0 +1,79 @@
package main
import (
"testing"
)
var example = `6,10
0,14
9,10
0,3
10,4
4,11
6,0
6,12
4,1
0,13
10,12
3,4
3,0
8,4
1,10
2,14
8,10
9,0
fold along y=7
fold along x=5`
func Test_part1(t *testing.T) {
tests := []struct {
name string
input string
want int
}{
{
name: "example",
input: example,
want: 17,
},
// {
// name: "actual",
// input: input,
// want: 0,
// },
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := part1(tt.input); got != tt.want {
t.Errorf("part1() = %v, want %v", got, tt.want)
}
})
}
}
func Test_part2(t *testing.T) {
tests := []struct {
name string
input string
want int
}{
{
name: "example",
input: example,
want: 0,
},
// {
// name: "actual",
// input: input,
// want: 0,
// },
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := part2(tt.input); got != tt.want {
t.Errorf("part2() = %v, want %v", got, tt.want)
}
})
}
}
+173
View File
@@ -0,0 +1,173 @@
package main
import (
_ "embed"
"flag"
"fmt"
"strings"
"github.com/alexchao26/advent-of-code-go/cast"
"github.com/alexchao26/advent-of-code-go/data-structures/heap"
"github.com/alexchao26/advent-of-code-go/util"
)
//go:embed input.txt
var input string
func init() {
// do this in init (not main) so test file has same input
input = strings.TrimRight(input, "\n")
if len(input) == 0 {
panic("empty input.txt file")
}
}
func main() {
var part int
flag.IntVar(&part, "part", 1, "part 1 or 2")
flag.Parse()
fmt.Println("Running part", part)
if part == 1 {
ans := part1(input)
util.CopyToClipboard(fmt.Sprintf("%v", ans))
fmt.Println("Output:", ans)
} else {
ans := part2(input)
util.CopyToClipboard(fmt.Sprintf("%v", ans))
fmt.Println("Output:", ans)
}
}
func part1(input string) int {
grid := parseInput(input)
_ = grid
for i, rows := range grid {
for j := range rows {
if i == 0 && j == 0 {
continue
} else if i == 0 {
grid[i][j] += grid[i][j-1]
} else if j == 0 {
grid[i][j] += grid[i-1][j]
} else {
if grid[i-1][j] < grid[i][j-1] {
grid[i][j] += grid[i-1][j]
} else {
grid[i][j] += grid[i][j-1]
}
}
}
}
return grid[len(grid)-1][len(grid[0])-1] - grid[0][0]
}
func part2(input string) int {
// make the grid 5 times larger
// add 1 to every cell when moving right OR down (so diagonal is +2)
// 9 wraps back to 1
grid := parseInput(input)
bigGrid := make([][]int, len(grid)*5)
for i := range bigGrid {
bigGrid[i] = make([]int, len(grid[0])*5)
}
for r, row := range grid {
for c, v := range row {
bigGrid[r][c] = v
}
}
assignGrid := func(baseGrid [][]int, newGrid [][]int, r, c int) {
for i := 0; i < len(newGrid); i++ {
for j := 0; j < len(newGrid[0]); j++ {
baseGrid[r+i][c+j] = newGrid[i][j]
}
}
}
incrementGrid := func(baseGrid [][]int, by int) [][]int {
newGrid := make([][]int, len(baseGrid))
for i := range newGrid {
newGrid[i] = make([]int, len(baseGrid[0]))
}
for i := range baseGrid {
for j := range baseGrid[0] {
newGrid[i][j] = baseGrid[i][j] + by
for newGrid[i][j] > 9 {
newGrid[i][j] -= 9
}
}
}
return newGrid
}
for r := 0; r < 5; r++ {
for c := 0; c < 5; c++ {
if r == 0 && c == 0 {
continue
}
nextGrid := incrementGrid(grid, r+c)
assignGrid(bigGrid, nextGrid, r*len(grid), c*len(grid[0]))
}
}
minHeap := heap.NewMinHeap()
minHeap.Add(node{0, 0, 0})
visited := map[[2]int]bool{}
for minHeap.Length() > 0 {
front := minHeap.Remove().(node)
coord := [2]int{front.row, front.col}
// moving this check here instead of in the heap.Add() makes a HUGE difference
// by reducing the swell of the queue and following computations
if visited[coord] {
continue
}
visited[[2]int{front.row, front.col}] = true
if front.row == len(bigGrid)-1 && front.col == len(bigGrid[0])-1 {
return front.risk
}
// travel to all of front's neighbors
for _, d := range [][2]int{
{0, 1},
{1, 0},
{0, -1},
{-1, 0},
} {
nr, nc := front.row+d[0], front.col+d[1]
if nr >= 0 && nr < len(bigGrid) && nc >= 0 && nc < len(bigGrid[0]) {
minHeap.Add(node{
row: nr,
col: nc,
risk: front.risk + bigGrid[nr][nc],
})
}
}
}
panic("should return from loop")
}
// A* node
type node struct {
row, col int
risk int
}
func (n node) Value() int {
return n.risk
}
func parseInput(input string) (ans [][]int) {
for _, line := range strings.Split(input, "\n") {
var row []int
for _, char := range strings.Split(line, "") {
row = append(row, cast.ToInt(char))
}
ans = append(ans, row)
}
return ans
}
+68
View File
@@ -0,0 +1,68 @@
package main
import (
"testing"
)
var example = `1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581`
func Test_part1(t *testing.T) {
tests := []struct {
name string
input string
want int
}{
{
name: "example",
input: example,
want: 40,
},
{
name: "actual",
input: input,
want: 811,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := part1(tt.input); got != tt.want {
t.Errorf("part1() = %v, want %v", got, tt.want)
}
})
}
}
func Test_part2(t *testing.T) {
tests := []struct {
name string
input string
want int
}{
{
name: "example",
input: example,
want: 315,
},
{
name: "actual",
input: input,
want: 3012,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := part2(tt.input); got != tt.want {
t.Errorf("part2() = %v, want %v", got, tt.want)
}
})
}
}
+198
View File
@@ -0,0 +1,198 @@
package main
import (
_ "embed"
"flag"
"fmt"
"strconv"
"strings"
"github.com/alexchao26/advent-of-code-go/mathy"
"github.com/alexchao26/advent-of-code-go/util"
)
//go:embed input.txt
var input string
func init() {
// do this in init (not main) so test file has same input
input = strings.TrimRight(input, "\n")
if len(input) == 0 {
panic("empty input.txt file")
}
}
func main() {
var part int
flag.IntVar(&part, "part", 1, "part 1 or 2")
flag.Parse()
fmt.Println("Running part", part)
if part == 1 {
ans := part1(input)
util.CopyToClipboard(fmt.Sprintf("%v", ans))
fmt.Println("Output:", ans)
} else {
ans := part2(input)
util.CopyToClipboard(fmt.Sprintf("%v", ans))
fmt.Println("Output:", ans)
}
}
func part1(input string) int64 {
bin := parseInput(input)
versionTotal, _, _ := handlePacket(bin)
return versionTotal
}
// bitsRead is often just called n in Go. See io.Read() for example
func handlePacket(pack string) (versionTotal int64, expressionValue int, bitsRead int) {
version, err := strconv.ParseInt(pack[0:3], 2, 64)
versionTotal += version
if err != nil {
panic("version strconv.ParseInt(): " + err.Error())
}
typeID, err := strconv.ParseInt(pack[3:6], 2, 64)
if err != nil {
panic("typeID strconv.ParseInt(): " + err.Error())
}
read := 6 // version and typeID
switch typeID {
case 4: // literal value
// parse 5 bits at a time
var bits string
for i := 6; i < len(pack); i += 5 {
fiveBits := pack[i : i+5]
read += 5
bits += fiveBits[1:]
if fiveBits[0] == '0' {
break
}
}
decimalVal, err := strconv.ParseInt(bits, 2, 64)
if err != nil {
panic("parsing packet bits: " + err.Error())
}
return version, int(decimalVal), read
default: // operator types?
// contains one or more packets
lengthTypeID := pack[6:7]
read++
var bitsToRead int
switch lengthTypeID {
case "0":
// next 15 bits == total length in bits for REST of subpackets
bitsToRead = 15
case "1":
// next 11 bits == NUMBER of subpackets
bitsToRead = 11
}
rawLength := pack[7 : 7+bitsToRead]
read += bitsToRead
length, err := strconv.ParseInt(rawLength, 2, 64)
if err != nil {
panic("parsing 0 lengthTypeID: " + err.Error())
}
// followed by the subpackets themselves
var subPacketExpressionValues []int
switch lengthTypeID {
case "0":
// next 15 bits == total length in bits for REST of subpackets
for length > 0 {
// continue reading until length of bits are read
ver, expVal, n := handlePacket(pack[read:])
read += n
length -= int64(n)
subPacketExpressionValues = append(subPacketExpressionValues, expVal)
versionTotal += ver
}
case "1":
// next 11 bits == NUMBER of subpackets
for length > 0 {
// continue reading until number of packets are read
ver, expVal, n := handlePacket(pack[read:])
read += n
length-- // reduce length by 1 (ie one packet read)
subPacketExpressionValues = append(subPacketExpressionValues, expVal)
versionTotal += ver
}
}
switch typeID {
// note: case 0 already handled above, literal value
case 0: // sum
return versionTotal, mathy.SumIntSlice(subPacketExpressionValues), read
case 1: // product
return versionTotal, mathy.MultiplyIntSlice(subPacketExpressionValues), read
case 2: // min
return versionTotal, mathy.MinInt(subPacketExpressionValues...), read
case 3: // max
return versionTotal, mathy.MaxInt(subPacketExpressionValues...), read
// 4 is literal...
case 5: // greater than (first subpacket > second, will always have exactly 2)
var ans int
if subPacketExpressionValues[0] > subPacketExpressionValues[1] {
ans = 1 // otherwise int zero val works
}
return versionTotal, ans, read
case 6: // less than (opposite)
var ans int
if subPacketExpressionValues[0] < subPacketExpressionValues[1] {
ans = 1 // otherwise int zero val works
}
return versionTotal, ans, read
case 7: // equal to
var ans int
if subPacketExpressionValues[0] == subPacketExpressionValues[1] {
ans = 1 // otherwise int zero val works
}
return versionTotal, ans, read
default:
panic(fmt.Sprintf("unknown typeID: %d", typeID))
}
}
}
func part2(input string) int {
bin := parseInput(input)
_, expVal, _ := handlePacket(bin)
return expVal
}
var hexToBin = map[string]string{
"0": "0000",
"1": "0001",
"2": "0010",
"3": "0011",
"4": "0100",
"5": "0101",
"6": "0110",
"7": "0111",
"8": "1000",
"9": "1001",
"A": "1010",
"B": "1011",
"C": "1100",
"D": "1101",
"E": "1110",
"F": "1111",
}
func parseInput(input string) string {
var binarySb strings.Builder
for _, char := range strings.Split(input, "") {
binarySb.WriteString(hexToBin[char])
}
return binarySb.String()
}
+129
View File
@@ -0,0 +1,129 @@
package main
import (
_ "embed"
"testing"
)
func Test_part1(t *testing.T) {
tests := []struct {
name string
input string
want int64
}{
{
name: "example1",
input: "8A004A801A8002F478",
want: 16,
},
{
name: "example2",
input: "620080001611562C8802118E34",
want: 12,
},
{
name: "example3",
input: "C0015000016115A2E0802F182340",
want: 23,
},
{
name: "example4",
input: "A0016C880162017C3686B18A3D4780",
want: 31,
},
{
name: "actual",
input: input,
want: 953,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := part1(tt.input); got != tt.want {
t.Errorf("part1() = %v, want %v", got, tt.want)
}
})
}
}
func Test_part2(t *testing.T) {
tests := []struct {
name string
input string
want int
}{
{
name: "example",
input: "C200B40A82",
want: 3,
},
{
name: "example",
input: "04005AC33890",
want: 54,
},
{
name: "example",
input: "880086C3E88112",
want: 7,
},
{
name: "example",
input: "CE00C43D881120",
want: 9,
},
{
name: "example",
input: "D8005AC2A8F0",
want: 1,
},
{
name: "example",
input: "F600BC2D8F",
want: 0,
},
{
name: "example",
input: "9C005AC2F8F0",
want: 0,
},
{
name: "example",
input: "9C0141080250320F1802104A08",
want: 1,
},
{
name: "actual",
input: input,
want: 246225449979,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := part2(tt.input); got != tt.want {
t.Errorf("part2() = %v, want %v", got, tt.want)
}
})
}
}
// func Test_handlePacket(t *testing.T) {
// tests := []struct {
// name string
// pack string
// want int
// }{
// {
// pack: "110100101111111000101000",
// want: 2021,
// },
// }
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// if got := handlePacket(tt.pack); got != tt.want {
// t.Errorf("handlePacket() = %v, want %v", got, tt.want)
// }
// })
// }
// }