mirror of
https://github.com/tiennm99/adventofcode.git
synced 2026-06-17 18:47:44 +00:00
feat(2025): add day9
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Pos struct {
|
||||
x int
|
||||
y int
|
||||
}
|
||||
|
||||
func parse(input string) []Pos {
|
||||
lines := []Pos{}
|
||||
sc := bufio.NewScanner(strings.NewReader(input))
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
if !strings.Contains(line, ",") {
|
||||
continue
|
||||
}
|
||||
i := strings.Index(line, ",")
|
||||
x, _ := strconv.Atoi(line[:i])
|
||||
y, _ := strconv.Atoi(line[i+1:])
|
||||
lines = append(lines, Pos{x, y})
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func part1(input string) int {
|
||||
lines := parse(input)
|
||||
maxArea := 0
|
||||
for i := range lines {
|
||||
x1, y1 := lines[i].x, lines[i].y
|
||||
for j := 0; j < i; j++ {
|
||||
x2, y2 := lines[j].x, lines[j].y
|
||||
area := (abs(x1-x2) + 1) * (abs(y1-y2) + 1)
|
||||
if area > maxArea {
|
||||
maxArea = area
|
||||
}
|
||||
}
|
||||
}
|
||||
return maxArea
|
||||
}
|
||||
|
||||
func part2(input string) int {
|
||||
lines := parse(input)
|
||||
n := len(lines)
|
||||
maxArea := 0
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
for i := range lines {
|
||||
x1, y1 := lines[i].x, lines[i].y
|
||||
for j := 0; j < i; j++ {
|
||||
x2, y2 := lines[j].x, lines[j].y
|
||||
|
||||
valid := true
|
||||
for k := 0; k < n; k++ {
|
||||
x3, y3 := lines[k].x, lines[k].y
|
||||
x4, y4 := lines[(k+1)%n].x, lines[(k+1)%n].y
|
||||
|
||||
// Non-overlap check
|
||||
if !(maxi(x3, x4) <= mini(x1, x2) ||
|
||||
maxi(x1, x2) <= mini(x3, x4) ||
|
||||
maxi(y3, y4) <= mini(y1, y2) ||
|
||||
maxi(y1, y2) <= mini(y3, y4)) {
|
||||
|
||||
valid = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if valid {
|
||||
area := (abs(x1-x2) + 1) * (abs(y1-y2) + 1)
|
||||
if area > maxArea {
|
||||
maxArea = area
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return maxArea
|
||||
}
|
||||
|
||||
func abs(a int) int {
|
||||
if a < 0 {
|
||||
return -a
|
||||
}
|
||||
return a
|
||||
}
|
||||
func mini(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
func maxi(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func main() {
|
||||
data, err := os.ReadFile("input.txt")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
input := string(data)
|
||||
|
||||
fmt.Println("Part 1:", part1(input))
|
||||
fmt.Println("Part 2:", part2(input))
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module day9
|
||||
|
||||
go 1.23.4
|
||||
Reference in New Issue
Block a user