Files
aoc2021/seven/crabs.go
2021-12-07 16:04:40 +00:00

71 lines
1.1 KiB
Go

package seven
import (
"bufio"
"math"
"os"
"strconv"
"strings"
)
type crabs struct {
crabs map[int]int
count int
max int
}
func (c *crabs) load(filename string) error {
c.crabs = map[int]int{}
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
initialPositions := strings.Split(scanner.Text(), ",")
for _, n := range initialPositions {
position, err := strconv.Atoi(n)
if err != nil {
return err
}
if position > c.max {
c.max = position
}
c.crabs[position]++
}
for _, count := range c.crabs {
c.count += count
}
}
return nil
}
func (c *crabs) align(notConstant bool) (fuel int) {
for i := 0; i < c.max; i++ {
fuelUsed := 0
for k, count := range c.crabs {
fuelPerCrab := int(math.Abs(float64(i - k)))
if notConstant {
for i := fuelPerCrab - 1; i > 0; i-- {
fuelPerCrab += i
}
}
fuelUsed += fuelPerCrab * count
}
if i == 0 || fuelUsed < fuel {
fuel = fuelUsed
}
}
return fuel
}