Advent Of Code 2024 – Day 1
I decided to do the Advent of Code in Julia, as a way of getting back into coding for fun.
Part 1
Given two lists of numbers, work out the distance between each entry in the list (after sorting the lists), then sum the distances to determine the “similarity”.
This is the first time I've written Julia code since 2023-09 , so it involved a lot of referring to the documentation, and it's not really taking advantage of any Julia language specific features (like all code blocks automatically returning their last value).
# Get the distance between two lists, after sorting them
function list_distances(lhs, rhs)
lhs_sorted = sort(lhs)
rhs_sorted = sort(rhs)
return map(lhs_sorted, rhs_sorted) do left, right
return abs(left - right)
end
end
function parse_input(src = "input.txt")
# Format of src
# ##### #####\n
lhs = Vector{Int}(undef, 0)
rhs = Vector{Int}(undef, 0)
for line in eachline(src)
lhs_substr = line[1:5]
rhs_substr = line[9:13]
l = parse(Int, lhs_substr; base=10)
r = parse(Int, rhs_substr; base=10)
push!(lhs, l)
push!(rhs, r)
end
return lhs, rhs
end
function main_part1()
lhs, rhs = parse_input()
list_dist = list_distances(lhs, rhs)
total_dist = sum(list_dist)
println("Total dist: ", total_dist)
end
main_part1()
Part 2
For each entry in a list, determine how often it appears in a second list, then multiply the entry by that frequency – then sum these factors.
For this one, I was a bit more warmed up and got a bit more concise in my Julia-isms. The algorithm used is just brute force, but it's Good Enough™ for this purpose.
Re-using parse_input
from Part 1.
function main_part2()
lhs, rhs = parse_input()
lhs_frequency = map(lhs) do l
count(==(l), rhs)
end
similarity = lhs .* lhs_frequency
println("Total similarity: ", sum(similarity))
end
main_part2()