62 lines
990 B
Go
62 lines
990 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"AoC2020/helper"
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"os"
|
||
|
"sort"
|
||
|
)
|
||
|
|
||
|
func main() {
|
||
|
args := os.Args[1:]
|
||
|
input, err := helper.GetInput(args[0])
|
||
|
if err != nil {
|
||
|
fmt.Println(err)
|
||
|
}
|
||
|
fmt.Println(day1(input))
|
||
|
fmt.Println(day1_part2(input))
|
||
|
|
||
|
}
|
||
|
|
||
|
func day1(numbers []int) int {
|
||
|
goal := 2020
|
||
|
sort.Ints(numbers)
|
||
|
p1 := 0
|
||
|
p2 := len(numbers) - 1
|
||
|
for {
|
||
|
if numbers[p1]+numbers[p2] < goal {
|
||
|
p1++
|
||
|
}
|
||
|
if numbers[p1]+numbers[p2] > goal {
|
||
|
p2--
|
||
|
}
|
||
|
if numbers[p1]+numbers[p2] == goal {
|
||
|
return numbers[p1] * numbers[p2]
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func day1_part2(numbers []int) (int, error) {
|
||
|
goal := 2020
|
||
|
sort.Ints(numbers)
|
||
|
|
||
|
for i, number := range numbers {
|
||
|
p1 := i + 1
|
||
|
p2 := len(numbers) - 1 - i
|
||
|
|
||
|
for p1 < p2 {
|
||
|
if numbers[p1]+numbers[p2]+number < goal {
|
||
|
p1++
|
||
|
}
|
||
|
if numbers[p1]+numbers[p2]+number > goal {
|
||
|
p2--
|
||
|
}
|
||
|
if numbers[p1]+numbers[p2]+number == goal {
|
||
|
return numbers[p1] * numbers[p2] * number, nil
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return 0, errors.New("No Triplet Found")
|
||
|
}
|