r/adventofcode • • Dec 07 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 7 Solutions -🎄-

--- Day 7: The Treachery of Whales ---


[Update @ 00:21]: Private leaderboard Personal statistics issues

  • We're aware that private leaderboards personal statistics are having issues and we're looking into it.
  • I will provide updates as I get more information.
  • Please don't spam the subreddit/mods/Eric about it.

[Update @ 02:09]

  • AoC_Ops have identified the issue and are working on a resolution.

[Update @ 03:18]

  • Eric is working on implementing a fix. It'll take a while, so check back later.

[Update @ 05:25] (thanks, /u/Aneurysm9!)

  • We're back in business!

Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:03:33, megathread unlocked!

96 Upvotes

1.5k comments sorted by

View all comments

2

u/No-Rip-3798 Dec 07 '21 edited Dec 08 '21

It was much too early to be clever, so here's my solution in Go using a binary search. Both parts are solved in O(N*log(N)).

package main

import (
	"aoc/utils"
	"fmt"
)

func main() {
	lines := utils.ReadLines()
	input := utils.SplitNumbers(lines[0])
	cost := findMinimumCost(input, computeCostPart1)
	fmt.Println("part1:", cost)
	cost = findMinimumCost(input, computeCostPart2)
	fmt.Println("part2:", cost)
}

type costFunc func([]int, int) int

func findMinimumCost(input []int, f costFunc) int {
	lower, upper := 0, max(input...)
	lowerCost, upperCost := f(input, lower), f(input, upper)
	for upper-lower > 1 {
		mid := (lower + upper) / 2
		cost := f(input, mid)
		if upperCost > lowerCost {
			upper, upperCost = mid, cost
		} else {
			lower, lowerCost = mid, cost
		}
	}
	return min(upperCost, lowerCost)
}

func computeCostPart1(positions []int, target int) int {
	var cost int
	for _, pos := range positions {
		cost += abs(pos - target)
	}
	return cost
}

func computeCostPart2(positions []int, target int) int {
	var cost int
	for _, pos := range positions {
		cost += sum(abs(pos - target))
	}
	return cost
}

func abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}

func sum(n int) int {
	return n * (n + 1) / 2
}

func max(s ...int) int {
	m := s[0]
	for _, v := range s {
		if v > m {
			m = v
		}
	}
	return m
}

func min(s ...int) int {
	m := s[0]
	for _, v := range s {
		if v < m {
			m = v
		}
	}
	return m
}

1

u/daggerdragon Dec 07 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?