day1 and 2 done & setup for day3
This commit is contained in:
parent
5053b3cbbd
commit
be09a5df2c
26 changed files with 2520 additions and 2 deletions
88
2021/day2/main.go
Normal file
88
2021/day2/main.go
Normal file
|
@ -0,0 +1,88 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func NewData(s string) Data {
|
||||
f := strings.Fields(s)
|
||||
a, err := strconv.Atoi(f[1])
|
||||
if err != nil {
|
||||
return Data{}
|
||||
}
|
||||
return Data{
|
||||
Direction: f[0],
|
||||
Amount: a,
|
||||
}
|
||||
}
|
||||
func GetData(s string) []Data {
|
||||
var data []Data
|
||||
r, err := os.Open(s)
|
||||
if err != nil {
|
||||
return data
|
||||
}
|
||||
fileScanner := bufio.NewScanner(r)
|
||||
fileScanner.Split(bufio.ScanLines)
|
||||
for fileScanner.Scan() {
|
||||
data = append(data, NewData(fileScanner.Text()))
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
type Data struct {
|
||||
Direction string
|
||||
Amount int
|
||||
}
|
||||
|
||||
func main() {
|
||||
data := GetData("./data")
|
||||
result := Part1(data)
|
||||
fmt.Printf("Result part 1: %d\n", result)
|
||||
result = Part2(data)
|
||||
fmt.Printf("Result part 1: %d\n", result)
|
||||
}
|
||||
|
||||
type Point struct {
|
||||
X int
|
||||
Y int
|
||||
Aim int
|
||||
}
|
||||
|
||||
func (p Point) Multiply() int {
|
||||
return p.Y * p.X
|
||||
}
|
||||
|
||||
func Part1(data []Data) int {
|
||||
var point Point
|
||||
for _, d := range data {
|
||||
switch d.Direction {
|
||||
case "forward":
|
||||
point.X += d.Amount
|
||||
case "down":
|
||||
point.Y += d.Amount
|
||||
case "up":
|
||||
point.Y -= d.Amount
|
||||
}
|
||||
}
|
||||
return point.Multiply()
|
||||
}
|
||||
|
||||
func Part2(data []Data) int {
|
||||
var point Point
|
||||
for _, d := range data {
|
||||
switch d.Direction {
|
||||
case "forward":
|
||||
point.X += d.Amount
|
||||
point.Y += point.Aim * d.Amount
|
||||
case "down":
|
||||
point.Aim += d.Amount
|
||||
case "up":
|
||||
point.Aim -= d.Amount
|
||||
}
|
||||
}
|
||||
return point.Multiply()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue