96 lines
1.8 KiB
Go
96 lines
1.8 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)
|
|
}
|
|
|
|
solution := make(chan int, 1)
|
|
for i := range numbers {
|
|
go func(a int) {
|
|
if r := checkTwoSums(numbers[a], numbers[a+1:]); r != 0 {
|
|
solution <- r
|
|
}
|
|
}(i)
|
|
}
|
|
fmt.Println(<-solution)
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
solution := make(chan int, 1)
|
|
|
|
for i := range numbers {
|
|
go func(a int) {
|
|
for j := range numbers[a+1:] {
|
|
if r := checkThreeSums(numbers[a], numbers[j], numbers[j+1:]); r != 0 {
|
|
solution <- r
|
|
}
|
|
}
|
|
}(i)
|
|
}
|
|
fmt.Println(<-solution)
|
|
}
|
|
|
|
func checkThreeSums(i int, j int, rest []int) int {
|
|
for _, k := range rest {
|
|
if i+j+k == 2020 {
|
|
return i * j * k
|
|
}
|
|
}
|
|
return 0
|
|
}
|