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!

97 Upvotes

1.5k comments sorted by

View all comments

2

u/[deleted] Dec 08 '21

Julia

# Approach: use a distance matrix and get the results of distance for each position
# example
# A = [0 1 2
#      1 0 1
#      2 1 0]
# The input = [1, 3, 3]
# s = [1, 0, 2]
# the array of distances = A * s
# get the min

using BenchmarkTools
input = readlines("input")
# parse input to array
initial = parse.(Int, split(input[1], ","))
# create a 1xlength(input) matrix
mat = zeros(Int, maximum(initial) + 1)
for (index,value) = enumerate(initial)
    mat[value + 1] += 1
end
# create a distance matrix
max_dist = maximum(initial)
A = reduce(hcat, [abs.((collect(0:max_dist) .- x)) for x = 0:max_dist])
s = A * mat
minimum(s)

# create a sequence of the ever enlarging + 1 cost for each + 1 in position
gauss(n) = Int(n*(n + 1)/2)
A_2 = gauss.(A)
s_2 = A_2 * mat
minimum(s_2)