2021 Day 17 Complete

This commit is contained in:
Brian Buller 2021-12-17 13:06:03 -06:00
parent 5aaf7163dc
commit ca81bb3b92
4 changed files with 101 additions and 16 deletions

1
2021/day17/input Normal file
View File

@ -0,0 +1 @@
target area: x=277..318, y=-92..-53

62
2021/day17/main.go Normal file
View File

@ -0,0 +1,62 @@
package main
import (
"fmt"
h "git.bullercodeworks.com/brian/adventofcode/helpers"
)
// Target Area
var x1, y1, x2, y2 int
func main() {
inp := h.StdinToString()
fmt.Sscanf(inp, "target area: x=%d..%d, y=%d..%d", &x1, &x2, &y1, &y2)
var maxy int
r := make(map[h.Coordinate]bool)
b := 500
for x := b * -1; x < b; x++ {
for y := b * -1; y < b; y++ {
v := h.Coordinate{X: x, Y: y}
if m, ok := testForHit(h.Coordinate{}, v); ok {
if m > maxy {
maxy = m
}
r[v] = true
}
}
}
fmt.Println("Maximum Peak:", maxy)
fmt.Println("Valid Velocities:", len(r))
}
func testForHit(pos h.Coordinate, vel h.Coordinate) (int, bool) {
var maxy int
for {
pos.X += vel.X
pos.Y += vel.Y
if pos.Y > maxy {
maxy = pos.Y
}
if pos.X >= x1 && pos.X <= x2 && pos.Y >= y1 && pos.Y <= y2 {
return maxy, true
}
if vel.X == 0 && vel.Y < y1 {
return maxy, false
}
if vel.X > 0 {
vel.X--
}
if vel.X < 0 {
vel.X++
}
vel.Y--
}
}
type xy struct {
x int
y int
}

1
2021/day17/testinput Normal file
View File

@ -0,0 +1 @@
target area: x=20..30, y=-10..-5

View File

@ -108,6 +108,16 @@ func OptArgNumber(i int, def string) string {
return def
}
// StdinToString reads from stdin and returns a string
func StdinToString() string {
var input string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
input += scanner.Text()
}
return input
}
// StdinToIntSlice reads from stdin and returns it as an int slice
func StdinToIntSlice() []int {
var ret []int
@ -148,16 +158,6 @@ func Itoa(i int) string {
return strconv.Itoa(i)
}
// StdinToString reads from stdin and returns a string
func StdinToString() string {
var input string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
input += scanner.Text()
}
return input
}
// FileToStringSlice takes a file and returns it as a slice of strings
func FileToStringSlice(fn string) []string {
return strings.Split(string(FileToBytes(fn)), "\n")
@ -358,16 +358,37 @@ func IsPrime(value int) bool {
return value > 1
}
func Min(v1, v2 int) int {
func Min(v1, v2 int, vrest ...int) int {
min := v2
if v1 < v2 {
return v1
min = v1
}
return v2
for i := range vrest {
if vrest[i] < min {
min = vrest[i]
}
}
return min
}
func Max(v1, v2 int) int {
func Max(v1, v2 int, vrest ...int) int {
max := v2
if v1 > v2 {
return v1
max = v1
}
return v2
for i := range vrest {
if vrest[i] > max {
max = vrest[i]
}
}
return max
}
// Sum adds up all of the numbers from l to h
func Sum(l, h int) int {
var ret int
for i := Min(l, h); i <= Max(l, h); i++ {
ret = ret + i
}
return ret
}