Day 01
This commit is contained in:
41
src/Year_2024/Day_01.jl
Normal file
41
src/Year_2024/Day_01.jl
Normal file
@@ -0,0 +1,41 @@
|
||||
using BenchmarkTools
|
||||
using StatsBase
|
||||
|
||||
function Day_01()
|
||||
# Robust file reading and parsing
|
||||
list_nums = Vector{Int}()
|
||||
open("files/P1.txt", "r") do file
|
||||
for line in eachline(file)
|
||||
# Split the line and parse the first two numbers
|
||||
nums = split(strip(line))
|
||||
if length(nums) >= 2
|
||||
push!(list_nums, parse(Int, nums[1]))
|
||||
push!(list_nums, parse(Int, nums[2]))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Preallocate arrays and use views to avoid unnecessary allocations
|
||||
l1 = view(list_nums, 1:2:length(list_nums))
|
||||
l2 = view(list_nums, 2:2:length(list_nums))
|
||||
|
||||
# Sort in-place to reduce memory allocations
|
||||
sort!(l1)
|
||||
sort!(l2)
|
||||
|
||||
# Optimized part 1: Use broadcast with a temporary array to avoid repeated allocations
|
||||
p1 = sum(abs, l1 .- l2)
|
||||
|
||||
# Optimized part 2: Use dictionary for efficient counting and avoid multiple passes
|
||||
freq = Dict{Int, Int}()
|
||||
for x in l2
|
||||
freq[x] = get(freq, x, 0) + 1
|
||||
end
|
||||
|
||||
p2 = sum(x -> x * get(freq, x, 0), l1)
|
||||
|
||||
return p1, p2
|
||||
end
|
||||
|
||||
println(Day_01())
|
||||
@btime Day_01()
|
||||
Reference in New Issue
Block a user