package main

import (
	"AOC2021/src/helper"
	"fmt"
	"os"
	"strings"
)

func main() {
	args := os.Args[1:]
	input, err := helper.GetInput(args[0])
	if err != nil {
		fmt.Println(err)
	}
	inputNumbers, _ := helper.MapToNumber(strings.Split(input[0], ","))
	crabMap := make(map[int]int)
	maxPosition := 0
	for _, inputNumber := range inputNumbers {
		if maxPosition < inputNumber {
			maxPosition = inputNumber
		}
		crabMap[inputNumber] += 1
	}

	lowestFuelConsumption := calculate(crabMap, maxPosition/2, 9999999999)
	for i:= 0; i < maxPosition; i++ {
		fuelConsumption :=calculate(crabMap, i, lowestFuelConsumption)
		if  fuelConsumption < lowestFuelConsumption {
			lowestFuelConsumption = fuelConsumption
		}
	}
	fmt.Println(lowestFuelConsumption)

}

func calculate(crabMap map[int]int, goalPosition int, currentLowestFullConsumption int) int {
	sum := 0
	for positionCrab, amount := range crabMap {
		distance := helper.Abs(positionCrab-goalPosition)
		sum += ((distance) * (distance + 1)/2) * amount
		if sum > currentLowestFullConsumption {
			return sum
		}
	}
	return sum
}
