This repository has been archived on 2021-12-06. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
adventofcode/pkg/one/one.go
T

81 lines
1.2 KiB
Go
Raw Normal View History

2021-12-01 11:41:37 +01:00
package one
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
)
func Run() {
2021-12-02 13:22:27 +01:00
fmt.Printf("1st solution: %d\n", solveFirst())
2021-12-02 16:12:40 +01:00
fmt.Printf("2nd solution: %d\n", solveSecond())
2021-12-01 11:41:37 +01:00
}
2021-12-02 13:22:27 +01:00
func readInput() []int {
2021-12-01 11:41:37 +01:00
file, err := os.Open("./pkg/one/input.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
numbers := make([]int, 0)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
num, err := strconv.Atoi(scanner.Text())
if err != nil {
log.Fatal(err)
}
numbers = append(numbers, num)
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return numbers
}
2021-12-02 13:22:27 +01:00
func solveFirst() int {
2021-12-01 11:41:37 +01:00
p := 0
i := 0
2021-12-02 13:22:27 +01:00
for k, v := range readInput() {
2021-12-01 11:41:37 +01:00
if k == 0 {
p = v
continue
}
if p < v {
i++
}
p = v
}
2021-12-02 13:22:27 +01:00
return i
2021-12-01 11:41:37 +01:00
}
2021-12-02 13:22:27 +01:00
func solveSecond() int {
2021-12-01 11:41:37 +01:00
increasedMeasurements := 0
a := make([]int, 3)
b := make([]int, 3)
2021-12-02 13:22:27 +01:00
numbers := readInput()
2021-12-01 11:41:37 +01:00
for i := 0; i < len(numbers); i++ {
if i+4 <= len(numbers) {
a = numbers[i : i+3]
b = numbers[i+1 : i+4]
aSum := 0
bSum := 0
for _, v := range a {
aSum += v
}
for _, v := range b {
bSum += v
}
if bSum > aSum {
increasedMeasurements++
}
}
}
2021-12-02 13:22:27 +01:00
return increasedMeasurements
2021-12-01 11:41:37 +01:00
}