package main

import (
	"AoC2020/helper"
	"errors"
	"fmt"
	"os"
	"sort"
)

func main() {
	args := os.Args[1:]
	input, err := helper.GetInput(args[0])
	fmt.Println(input)
	if err != nil {
		fmt.Println(err)
	}
	numbers, err := helper.MapToNumber(input)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(day1(numbers))
	fmt.Println(day1_part2(numbers))
}

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")
}
