89 lines
1.7 KiB
Go
89 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
)
|
|
|
|
func main() {
|
|
partOne()
|
|
partTwo()
|
|
}
|
|
|
|
// [...] they need you to find the two entries that sum to 2020 and then multiply those two numbers together.
|
|
// For example, suppose your expense report contained the following:
|
|
// 1721
|
|
// 979
|
|
// 366
|
|
// 299
|
|
// 675
|
|
// 1456
|
|
// In this list, the two entries that sum to 2020 are 1721 and 299.
|
|
// Multiplying them together produces 1721 * 299 = 514579, so the correct answer is 514579.
|
|
|
|
func partOne() {
|
|
f, _ := os.Open("input")
|
|
reader := bufio.NewReader(f)
|
|
scanner := bufio.NewScanner(reader)
|
|
|
|
numbers := []int{}
|
|
|
|
for scanner.Scan() {
|
|
i, _ := strconv.Atoi(scanner.Text())
|
|
numbers = append(numbers, i)
|
|
}
|
|
|
|
for i := range numbers {
|
|
if result := checkTwoSums(numbers[i], numbers[i+1:]); result != 0 {
|
|
fmt.Println(result)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func checkTwoSums(i int, rest []int) int {
|
|
for _, j := range rest {
|
|
if i+j == 2020 {
|
|
return i * j
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// Can find three numbers in your expense report that meet the same criteria?
|
|
// Using the above example again, the three entries that sum to 2020 are 979, 366, and 675.
|
|
// Multiplying them together produces the answer, 241861950.
|
|
|
|
func partTwo() {
|
|
f, _ := os.Open("input")
|
|
reader := bufio.NewReader(f)
|
|
scanner := bufio.NewScanner(reader)
|
|
|
|
numbers := []int{}
|
|
|
|
for scanner.Scan() {
|
|
i, _ := strconv.Atoi(scanner.Text())
|
|
numbers = append(numbers, i)
|
|
}
|
|
|
|
for i := range numbers {
|
|
for j := range numbers[i+1:] {
|
|
if result := checkThreeSums(numbers[i], numbers[j], numbers[j+1:]); result != 0 {
|
|
fmt.Println(result)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func checkThreeSums(i int, j int, rest []int) int {
|
|
for _, k := range rest {
|
|
if i+j+k == 2020 {
|
|
return i * j * k
|
|
}
|
|
}
|
|
return 0
|
|
}
|