package day09

import (
	_ "fmt"
	"strings"
	
	"adventofcode2023/utils/inputs"

)

func Part1(input string) int {
	ins := parseInput(input)
	ans := 0 
	for _, in := range ins {
		ans += f1(in)
	} 
	return ans
}

func Part2(input string) int {
	ins := parseInput(input)
	ans := 0 
	for _, in := range ins {
		reverse(in)
		ans += f1(in)
	} 
	return ans}

func f1(in []int) int {
	out := []int{}
	for i:=0;i<len(in)-1;i++{
		out = append(out, in[i+1] - in[i])
	}
	if allZero(out) {
		return in[len(in) -1]
	} else {
		return in[len(in) -1] + f1(out)
	}
}

func reverse(nums []int) {
    for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 {
        nums[i], nums[j] = nums[j], nums[i]
    }
}

func allZero(in []int) bool {
	for _, v := range in {
		if v != 0 {
			return false
		}
	}
	return true
}

func diff(in []int) []int {
	out := []int{}
	for i:=0;i<len(in)-1;i++{
		out = append(out, in[i+1] - in[i])
	}
	return out
}

func parseInput(input string) ([][]int) {
	lines := strings.Split(input, "\n")
	out := [][]int{}
	for _, line := range lines {
		out = append(out, inputs.ToInts(line, " "))
	}
 	return out
}