You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# initialization
elf_calories =0# stores calories for each elf
max_elf_calories =0# stores maximum calories
list_elf_calories = [] # A list to store each elf's total calories for l in calories
if!isempty(l)
elf_calories += l
elseif elf_calories > max_elf_calories
max_elf_calories = elf_calories
end
list_elf_calories =push!(list_elf_calories, elf_calories)
elf_calories =0endendsort!(list_elf_calories, rev =true) # sorting in decending order
top_three_elf_Calories =sum(list_elf_calories[1:n]) # adding top 3 return max_elf_calories, top_three_elf_Calories
end# read input file
calories =readdlm("data/input_day01.txt", skipblanks=false)
max_cal, max_n_cal =max_elf_calories(calories, 3)
println("Part 1: The total calories are: ", max_cal)
println("Part 2: The total calories carrying by the top three elfs are :", max_n_cal)
Day 02:
Part 01:
functiontotal_score(guide)
total_score =0
winner_rule = ["A Y", "B Z", "C X"] # rules for winn
lose_rule = ["A Z", "B X", "C Y"] # rules for loss
draw_rule = ["A X", "B Y", "C Z"] # rules for drawfor item in guide
if item in winner_rule
total_score +=endswith(item, "X") ?7:endswith(item, "Y") ?8:9endif item in lose_rule
total_score +=endswith(item, "X") ?1:endswith(item, "Y") ?2:3endif item in draw_rule
total_score +=endswith(item, "X") ?4:endswith(item, "Y") ?5:6endendreturn total_score
end
Part 02:
functiontotal_score_with_diff_Strategy(guide)
new_score =0
winner_rule = ["A Y", "B Z", "C X"] #
loss_rule = ["A Z", "B X", "C Y"]
draw_rule = ["A X", "B Y", "C Z"]
for item in guide
# This block defines our new strategy for winningifendswith(item, "Z")
temp = winner_rule[findfirst(contains(first(item)), winner_rule)]
new_score +=endswith(temp, "X") ?7:endswith(temp, "Y") ?8:9end# This block defines our new strategy for losingifendswith(item, "X")
temp = loss_rule[findfirst(contains(first(item)), loss_rule)]
new_score +=endswith(temp, "X") ?1:endswith(temp, "Y") ?2:3end# This block defines our new strategy for drawifendswith(item, "Y")
temp = draw_rule[findfirst(contains(first(item)), draw_rule)]
new_score +=endswith(temp, "X") ?4:endswith(temp, "Y") ?5:6endendreturn new_score
end
Day 03:
Part 01:
functionsame_items(data::Vector{String}, priorities::Dict)
total_sum::Int64=0for str in data
common_item = str[1:length(str) ÷2] ∩ str[length(str) ÷2+1:end] # \cap + <TAB> for intersection (∩) symbol \div + <TAB> for ÷ symbol
total_sum += priorities[common_item[1]]
endreturn total_sum
end
data =readlines("data/input_day03.txt")
numbers =collect(1:52)
alphabets =collect("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
priorities =Dict(alphabets[i] => numbers[i] for i in1:52)
println("Part 01: Sum of the prioroties of common items: ", same_items(data, priorities))
println("Part 02: Sum of priorities of badge items: ", badge_items(data, priorities))
Day 04:
functioncamp_cleanup(input::Vector{String})
common_count::Int64=0
overlap_count::Int64=0
assignment =map(s->parse.(Int64, s), split.(input, r"\-|,"))
for pairs in assignment
intersect(pairs[1]:pairs[2], pairs[3]:pairs[4]) ∈ (pairs[1]:pairs[2], pairs[3]:pairs[4]) ? common_count +=1:nothing!isempty(intersect(pairs[1]:pairs[2], pairs[3]:pairs[4])) ? overlap_count +=1:nothingendreturn [common_count, overlap_count]
end
Day 05:
functionparse_data(crates_data)
total_stacks =split(crates_data[end])
# Create empty crates to fill with data later
stacks = [Stack{Char}() for i in1:length(total_stacks)]
for i inlength(crates_data)-1:-1:1
crate = crates_data[i][2:4:end]
for j in1:length(crate)
!isequal(crate[j], '') ?push!(stacks[j], crate[j]) :nothingendendreturn stacks
end
functionday_05(stacks_01, stacks_02, instructions)
for i in instructions
if!isempty(i)
m =match(r".*(?<crate> \d+) .* (?<from>\d+) .* (?<to>\d+)", i)
crate, from, to =parse.(Int, m)
# Part 1:
pop_items_1 = [pop!(stacks_01[from]) for i in1:crate]
[push!(stacks_01[to], j) for j in pop_items_1]
# Part 2:
pop_items_02 =reverse!([pop!(stacks_02[from]) for i in1:crate])
[push!(stacks_02[to], j) for j in pop_items_02]
endendreturn [String([first(c) for c in stacks_01]), String([first(c) for c in stacks_02])]
end
# using DataStructures # This package is required to run this code.
input =read("data/input_day05.txt", String)
crates, instructions =split.(split(input, "\n\n"), "\n")
part_01 =parse_data(crates)
part_02 =parse_data(crates)
top_crate_1, top_crate_2=day_05(part_01, part_02, instructions)
println("Part 01: Top crates are: ", top_crate_1)
println("Part 02: Top crates are: ", top_crate_2)
Day 06:
functionunique_marker(datastream, marker_size)
buffer::Vector{Char}= []
for signal in datastream
for i in1:length(signal) # charactersappend!(buffer, signal[i])
ifisequal(length(buffer), marker_size)
allunique(buffer) ? [return i] :popfirst!(buffer)
endendendend
data =split(read("data/input_day06.txt", String), "\n")
println("Part 1: Total characters to process are: ", unique_marker(data, 4))
println("Part 2: Total characters to process are: ", unique_marker(data, 14))
Day 07:
using PEG
using Test
functionhandle_dir(words)
return words
endfunctionhandle_file(files)
path =join(dir_path);
ifget(dirSize, path, "nothing") =="nothing"append!(dirSize[path], files[1])
else
dirSize[path] = dirSize[path] + files[1]
tmpDir =deepcopy(dir_path)
pop!(tmpDir)
whilelength(tmpDir) >0
dirSize[join(tmpDir)] = dirSize[join(tmpDir)] + files[1]
pop!(tmpDir)
endendreturn files
endfunctionhandle_cmd(words)
if words[3] =="cd"if words[5] ==".."pop!(dir_path)
elsepush!(dir_path, words[5])
dirSize[join(dir_path)] =0endendreturn words
endfunctionday_07(data::Vector{SubString{String}}, part::Int64)
global dir_path = String[]
global dirSize =Dict{String,Int64}()
# Rules for parsing the input data@rule cmdSpace =r"\s*"@rule cmdStart ="\$"@rule cmdArgs =r"[\.a-z\s\/]*"@rule cmd =r"[a-z]+"@rule sizeRule =r"[0-9]+"|> x ->parse(Int, x)
@rule iCmd = cmdStart & cmdSpace & cmd & cmdSpace & cmdArgs |> handle_cmd
@rule num = sizeRule & cmdArgs |> handle_file
@rule dire = cmd & cmdArgs |> handle_dir
@rule exper = iCmd, num, dire
[parse_whole(exper, l) for l in data]
# Part 1
part ==1&&returnsum([s for s invalues(dirSize) if s <=100000])
# Part 2if (part ==2)
total_size =70000000
size_needed =30000000
space_used = [dirSize[s] for s inkeys(dirSize) if s =="/"]
free_space = total_size - space_used[1]
space_Needed = size_needed - free_space
returnminimum([s for s invalues(dirSize) if s > space_Needed])
elsereturnerror("Part not implemented. Please provide a valid part number between 1 and 2.")
endend
test_input =split(read("data_aoc/test_day07.txt", String), "\n")
@test (day_07(test_input, 1) ==95437)
@test (day_07(test_input, 2) ==24933642)
data =split(read("data_aoc/input_day07.txt", String), "\n")
println("Part 1: The size of the total size is ", day_07(data, 1))
println("Part 2: The size of the directory to delete is ", day_07(data, 2))
Day 08:
functionget_visible_trees(data::Matrix{Int64}) # Part 1
visible_trees::Int64=0for x inaxes(data,1), y inaxes(data, 2)
curr_val = data[x,y]
top = data[begin:x-1, y]
bottom = data[x+1:end, y]
left = data[x, begin:y-1]
right = data[x, y+1:end]
if(curr_val .>maximum(top, init =-99) ||
curr_val >maximum(bottom, init =-99) ||
curr_val >maximum(left, init =-99) ||
curr_val >maximum(right, init =-99))
visible_trees +=1endendreturn visible_trees
end
unction get_scenic_score(data::Matrix{Int64})
scenic_score = Int[]
for x inaxes(data,1), y inaxes(data, 2)
curr_val = data[x,y]
top =reverse(data[begin:x-1, y])
bottom = (data[x+1:end, y])
left =reverse(data[x, begin:y-1])
right = (data[x, y+1:end])
top_score =isnothing(findfirst(curr_val .<= top)) ?length(top) :findfirst(curr_val .<= top)
bottom_score =isnothing(findfirst(curr_val .<= bottom)) ?length(bottom) :findfirst(curr_val .<= bottom)
left_score =isnothing(findfirst(curr_val .<= left)) ?length(left) :findfirst(curr_val .<= left)
right_score =isnothing(findfirst(curr_val .<= right)) ?length(right) :findfirst(curr_val .<= right)
push!(scenic_score, (top_score * bottom_score * left_score * right_score))
endreturnmaximum(scenic_score)
end
test_file ="data/test_day08.txt"
test_input =vcat(map(x->(parse.(Int64, x))', collect.(readlines(test_file)))...)
@test (get_visible_trees(test_input) ==21)
@test (get_scenic_score(test_input) ==8)
file ="data/input_day08.txt"
input =vcat(map(x->(parse.(Int64, x))', collect.(readlines(file)))...)
println("Part 01: Total number of trees visible are: ", get_visible_trees(input))
println("Part 02: The highest scenic score is: ", get_scenic_score(input))
Day 09:
Part 1:
functionday09_01(data)
tail_movements =0
visited_positions = Array{Int64,1}[]
head_movements = Array{Int64,1}[]
head_val = [0, 0]
tail_val = [0, 0]
#moves = U D L Rfor moves in data
direction, value =split(moves, "")
value =parse(Int, value)
for i in1:value
direction =="U"? head_val[2] +=1:
direction =="D"? head_val[2] -=1:
direction =="R"? head_val[1] +=1:
direction =="L"? head_val[1] -=1:nothingpush!(head_movements, copy(head_val))
if head_val[1] == tail_val[1] +2|| head_val[1] == tail_val[1] -2||
head_val[2] == tail_val[2] +2|| head_val[2] == tail_val[2] -2
tail_val[1] +=sign(head_val[1] - tail_val[1])
tail_val[2] +=sign(head_val[2] - tail_val[2])
elseif head_val[1] != tail_val[1] && head_val[2] != tail_val[2] &&
head_val[1] != tail_val[1] +1&& head_val[1] != tail_val[1] -1&&
head_val[2] != tail_val[2] +1&& head_val[2] != tail_val[2] -1
tail_val[1] +=sign(head_val[1] - tail_val[1])
tail_val[2] +=sign(head_val[2] - tail_val[2])
end#tail_movements += 1push!(visited_positions, copy(tail_val))
endendreturn visited_positions
end
Part 2:
functionday09_02(data)
ninth_tail_positions = Array{Int64,1}[]
head_movements = Array{Int64,1}[]
head_val = [0, 0]
all_tails = []
nine_tail_movements =0for k in1:9push!(all_tails, [0, 0])
endfor moves in data
direction, value =split(moves, "")
value =parse(Int, value)
for i in1:value
if direction =="U"
head_val[2] +=1elseif direction =="D"
head_val[2] -=1elseif direction =="R"
head_val[1] +=1elseif direction =="L"
head_val[1] -=1endpush!(head_movements, copy(head_val))
temp =deepcopy(head_val)
for j in1:9if temp[1] == all_tails[j][1] +2|| temp[1] == all_tails[j][1] -2||
temp[2] == all_tails[j][2] +2|| temp[2] == all_tails[j][2] -2
all_tails[j][1] +=sign(temp[1] - all_tails[j][1])
all_tails[j][2] +=sign(temp[2] - all_tails[j][2])
elseif temp[1] != all_tails[j][1] && temp[2] != all_tails[j][2] &&
temp[1] != all_tails[j][1] +1&& temp[1] != all_tails[j][1] -1&&
temp[2] != all_tails[j][2] +1&& temp[2] != all_tails[j][2] -1
all_tails[j][1] +=sign(temp[1] - all_tails[j][1])
all_tails[j][2] +=sign(temp[2] - all_tails[j][2])
end
temp =deepcopy(all_tails[j])
# nine_tail_movements += 1endpush!(ninth_tail_positions, copy(all_tails[9]))
endendreturn ninth_tail_positions
end
data =readlines("data_aoc/input_day09.txt");
visited_positions =day09_01(data);
ninth_tail_pos =day09_02(data);
println("Part 1: points that tail visited atleast once are: ", length(unique!(visited_positions)))
println("Part 2: points that 9th tail visited atleast once are: ", length(unique!(ninth_tail_pos)))
Day 10:
using DataStructures
functionday_10(data)
cycle_x =SortedDict()
X =1# initialize X
cycle =0#initial value of cycle
cycle_x[cycle] = X # add initial value to dictionaryfor instruction in data
if instruction =="noop"
cycle +=1
cycle_x[cycle] = X
elseifstartswith(instruction, "addx ")
cycle_x[cycle+1] = cycle_x[cycle+2] = X
cycle +=2
X +=parse(Int, instruction[6:end])
endendreturn cycle_x
end
input =readlines("data_aoc/input_day10.txt");
signal_strength =day_10(input);
sum_signal_Strength =sum([signal_strength[s] * s for s inkeys(signal_strength) if s in [20, 60, 100, 140, 180, 220]]);
println("Part 01: The sum of signal strength is: $(sum_signal_Strength). \n");
# Part 2
lit = [(mod((index-1), 40) in value -1:value +1?"#":".") for (index, value) inpairs(signal_strength)];
[(mod((i-1), 40) ==39?println(val) :print(val)) for (i, val) inenumerate(lit)];
Day 11:
# Parsing input datafunctionparse_input(data)
parsed_input = []
number = [parse(Int, filter(isnumeric, strip.(split(l, ""), ',')[2])) +1for l in data ifstartswith(l, "Monkey")]
items = [parse.(Int, strip.(split(l, ""), ',')[5:end]) for l in data ifcontains(l, "Starting items")]
operation = [eval(Meta.parse("old -> "* (split(l, " = "))[2])) for l in data ifcontains(l, "Operation")]
test = [parse(Int, (split(l, ""))[end]) for l in data ifcontains(l, "Test")]
if_true = [parse(Int, (split(l, ""))[end]) +1for l in data ifcontains(l, "If true")]
if_false = [parse(Int, (split(l, ""))[end]) +1for l in data ifcontains(l, "If false")]
for i in1:lastindex(number)
push!(parsed_input, (number[i], items[i], operation[i], test[i], if_true[i], if_false[i]))
endreturn parsed_input
end# Part 01:functionday11_part1(parsed_input)
total_time = []
for round in1:20for (monkey, info) inenumerate(parsed_input)
monkey_num, starting_items, op, test_val, true_place, false_place =deepcopy(info)
push!(total_time, ([monkey_num, length(starting_items)]))
for item in starting_items
new_item =Int(floor(op(item) /3))
target = new_item % test_val ==0? true_place : false_place
popfirst!(parsed_input[monkey][2])
push!(parsed_input[target][2], new_item)
endendendreturn total_time
end# Part 02:functionday11_part2(parsed_input, magic_number)
total_time = []
for round in1:10000for (monkey, info) inenumerate(parsed_input)
monkey_num, starting_items, op, test_val, true_place, false_place =deepcopy(info)
push!(total_time, ([monkey_num, length(starting_items)]))
for item in starting_items
new_item =op(item) % magic_number
target = new_item % test_val ==0? true_place : false_place
popfirst!(parsed_input[monkey][2])
push!(parsed_input[target][2], new_item)
endendendreturn total_time
end# computing total inspectionsfunctioncompute_total_inspections(total_time)
total_sum = []
[push!(total_sum, sum(filter(x -> x[1] == j, total_time))[2]) for j inunique!(map(x -> x[1], total_time))]
returnreduce(*, sort(total_sum, rev=true)[1:2])
end
data =readlines("data_aoc/input_day11.txt");
magic_number =lcm([parse(Int, (split(l, ""))[end]) for l in data ifcontains(l, "Test")]);
part_01 =compute_total_inspections(day11_part1(parse_input(data)));
part_02 =compute_total_inspections(day11_part2(parse_input(data), magic_number));
println("Part 1: Level of monkey business after 20 rounds is $(part_01). ")
println("Part 2: Level of monkey business after 10000 rounds is $(part_02).")
Day 12:
functioninput_parsing(data::Matrix{Char})
start_pos =findfirst(isequal('S'), data)
dest =findfirst(isequal('E'), data)
replace!(data, 'S'=>'a')
new_start_pos = (findall(isequal('a'), data))
return data, start_pos, dest, new_start_pos
endfunctioncompute_cost(data::Matrix{Char}, dest::CartesianIndex{2}, all_start_pos::Array{CartesianIndex{2},1})
elevation =Dict('a':'z'.=>0:25)
elevation['E'] =25
directions = ((0, -1), (0, 1), (1, 0), (-1, 0))
steps_required = Array{Any,1}[] # stores steps for each starting point to destinationfor start_pos in all_start_pos
steps =Dict{CartesianIndex{2},Int}()
steps[start_pos] =0# steps required to reach destination from start position a
queue = [start_pos]
while!isempty(queue)
current_loc =pop!(queue)
current_loc == dest ?push!(steps_required, [start_pos, steps[current_loc]]) :nothingfor (k, d) inenumerate(CartesianIndex.(directions))
new_loc = current_loc + d
checkbounds(Bool, data, new_loc) ||continueif ((elevation[data[new_loc]] - elevation[data[current_loc]]) <=1) &&!haskey(steps, new_loc)
steps[new_loc] = steps[current_loc] +1pushfirst!(queue, new_loc)
endendendendreturn steps_required
end
input_file =reduce(vcat, permutedims.(collect.(readlines("data_aoc/input_day12.txt"))));
data, start_pos, dest, new_start_pos =input_parsing(input_file);
steps_required =compute_cost(data, dest, new_start_pos);
[steps_required[start_pos][2], map(x ->values(x)[2], steps_required) |> minimum] |> println
Day 13:
using JSON
using BenchmarkTools
packets = JSON.parse.(filter(x ->length(x) >0, readlines("data_aoc/input_day13.txt")));
# My recursive functionfunctionright_order_pair(left::Any, right::Any)
ifisa(left, Integer) &&isa(right, Integer)
returncmp(left, right)
elseifisa(left, Integer)
returnright_order_pair([left], right)
elseifisa(right, Integer)
returnright_order_pair(left, [right])
elseifisa(left, Vector) &&isa(right, Vector)
ifisempty(left)
isempty(right) ?0:-1# left == right or left < rightelseifisempty(right)
return1# left > rightelseifright_order_pair(left[1], right[1]) ==0returnright_order_pair(left[2:end], right[2:end])
elsereturnright_order_pair(left[1], right[1])
endendendend# using my recursive function Part 1:@time (((i +1) ÷2) for i in1:2:length(packets) ifright_order_pair(packets[i], packets[i+1]) ==-1) |> sum |> println
# using builtin function # Rules for array and integer comparisons:
Base.isless(left::Vector{Any}, right::Integer) =isless(left, [right])
Base.isless(left::Integer, right::Vector{Any}) =isless([left], right)
Base.isequal(left::Vector{Any}, right::Integer) =isequal(left, [right])
Base.isequal(left::Integer, right::Vector{Any}) =isequal([left], right)
# part 1:@time (((i +1) ÷2) for i in1:2:length(packets) ifcmp(packets[i], packets[i+1]) ==-1) |> sum |> println
# Part 2:findall(packet -> packet in ([[[2]], [[6]]]), sort!(append!(packets, [[[2]], [[6]]]))) |> prod |> println
Day 14:
using DataStructures
functionparse_input(data::Vector{String})
cave = CartesianIndex{2}[]
for l in data
input_data = (map(x -> (parse.(Int, split(x, ","))), split(l, "->")))
coordinates = CartesianIndex{2}[] # to store the coordinates from the input
[push!(coordinates, CartesianIndex(points[1], points[2])) for points in input_data]
for i ineachindex(coordinates)
previous_index = coordinates[i]
if i <= (length(coordinates) -1)
current_index = coordinates[i+1]
if current_index[2] != previous_index[2]
ymin =min(previous_index[2], current_index[2])
ymax =max(previous_index[2], current_index[2])
[push!(cave, CartesianIndex(current_index[1], y)) for y in ymin:ymax]
endif current_index[1] != previous_index[1]
xmin =min(previous_index[1], current_index[1])
xmax =max(previous_index[1], current_index[1])
[push!(cave, CartesianIndex(x, current_index[2])) for x in xmin:xmax]
endendendendreturnpush!(unique!(cave), CartesianIndex(500, 0))
endfunctionprepare_cave_part1(cave::Vector{CartesianIndex{2}})
cave_map =SortedDict{CartesianIndex{2},Char}()
min_max =extrema(cave) # finding the min and max values of the cave coordinatesfor pt in min_max[1]:min_max[2]
pt in cave && pt !=CartesianIndex(500, 0) ?push!(cave_map, pt =>'#') :
pt ==CartesianIndex(500, 0) ?push!(cave_map, pt =>'+') :push!(cave_map, pt =>'.')
endreturn cave_map, min_max
endfunctionprepare_cave_part2(cave::Vector{CartesianIndex{2}})
min_max =extrema(cave)
y_max = (min_max[2]+CartesianIndex(0, 2))[2]
y_min = min_max[1][2]
sand_point =CartesianIndex(500, 0)
floor_for_sand =CartesianIndex((sand_point[1] - (y_max +1)), y_max):CartesianIndex((sand_point[1] + (y_max +1)), y_max)
[push!(cave, f) for f in floor_for_sand]
new_cave_cordinates =CartesianIndex(sand_point[1] - (y_max +1), y_min):CartesianIndex((sand_point[1] + (y_max +1)), y_max)
cave_map =SortedDict{CartesianIndex{2},Char}()
for pt in new_cave_cordinates
pt in cave && pt !=CartesianIndex(500, 0) ?push!(cave_map, pt =>'#') :
pt ==CartesianIndex(500, 0) ?push!(cave_map, pt =>'+') :push!(cave_map, pt =>'.')
endreturn cave_map, extrema(new_cave_cordinates)
endfunctionfalling_sand_part1(sand_point::CartesianIndex{2}, cave_map::SortedDict{CartesianIndex{2},Char}, y_max::Int64, x_min::Int64, x_max::Int64)
sand_moves = [CartesianIndex(0, 1), CartesianIndex(-1, 1), CartesianIndex(1, 1)]
whiletrue
possible_sand_moves = [sand_point + move for move in sand_moves]
next_sand_point = [p for p in possible_sand_moves ifhaskey(cave_map, p) && cave_map[p] =='.']
ifisempty(next_sand_point)
push!(cave_map, sand_point =>'o')
returntrueendif next_sand_point[1][1] <= x_min || next_sand_point[1][1] >= x_max || next_sand_point[1][2] >= y_max
breakend
sand_point = next_sand_point[1]
endreturnfalseendfunctionfalling_sand_part2(sand_point::CartesianIndex{2}, cave_map::SortedDict{CartesianIndex{2},Char}, y_max::Int64)
sand_moves = [CartesianIndex(0, 1), CartesianIndex(-1, 1), CartesianIndex(1, 1)]
while sand_point[2] < (y_max +2)
possible_sand_moves = [(sand_point + move) for move in sand_moves]
next_sand_point = [p for p in possible_sand_moves ifhaskey(cave_map, p) && cave_map[p] =='.']
if cave_map[CartesianIndex(500, 0)] =='o'breakendifisempty(next_sand_point)
push!(cave_map, sand_point =>'o')
returntrueend
sand_point = next_sand_point[1]
endreturnfalseend#for printing the cave mapfunctionprint_cave(cave_map, xmin, xmax)
for (index, value) inenumerate(cave_map)
(index -1) % ((xmax - xmin) +1) ==0?println() :print(value[2])
endprintln()
endfunctionday14_part1(cave::Vector{CartesianIndex{2}})
cave_map, min_max =prepare_cave_part1(cave)
sand_point =CartesianIndex(500, 0)
y_max = min_max[2][2]
x_min = min_max[1][1]
x_max = min_max[2][1]
sand_unit =0whiletrueif!(falling_sand_part1(sand_point, cave_map, y_max, x_min, x_max))
breakend
sand_unit +=1endprint_cave(cave_map, x_min, x_max)
return sand_unit
endfunctionday14_part2(cave::Vector{CartesianIndex{2}})
cave_map, min_max =prepare_cave_part2(cave)
sand_point =CartesianIndex(500, 0)
y_max = min_max[2][2]
x_min = min_max[1][1]
x_max = min_max[2][1]
sand_unit =0whiletrueif!(falling_sand_part2(sand_point, cave_map, y_max))
breakend
sand_unit +=1endprint_cave(cave_map, x_min, x_max)
return sand_unit
end
data =readlines("data_aoc/input_day14.txt");
println("Part 1: Number of sand units: ", day14_part1(parse_input(data)))
println("Part 2: Number of sand units: ", day14_part2(parse_input(data)))
Day 15:
using BenchmarkTools
functionparse_input()
data =split.(readlines("data_aoc/input_day15.txt"), ": ")
sensor_cord = Vector{Int64}[]
beacon_cord = Vector{Int64}[]
for sensor in data
x_sensor, y_sensor = [parse(Int, x[2]) for x insplit.(split(sensor[1][findfirst("x", sensor[1])[1]:end], ", "), "=")]
push!(sensor_cord, [x_sensor, y_sensor])
x_beacon, y_beacon = [parse(Int, x[2]) for x insplit.(split(sensor[2][findfirst("x", sensor[2])[1]:end], ", "), "=")]
push!(beacon_cord, [x_beacon, y_beacon])
endreturn sensor_cord, beacon_cord
endmanhattan(a::Vector{Int64}, b::Vector{Int64}) =sum(abs.((b - a)));
# Part 1:functionno_beacon_position(y_limit::Int64=2000000)
sensor_cord, beacon_cord =parse_input()
distance = [manhattan(sensor, beacon) for (sensor, beacon) inzip(sensor_cord, beacon_cord)]
range_dict::Vector{UnitRange}= []
for (sensor, dist) inzip(sensor_cord, distance)
min_val_x = sensor[1] - (dist -abs(sensor[2] - y_limit))
max_val_x = sensor[1] + (dist -abs(sensor[2] - y_limit))
push!(range_dict, (min_val_x:max_val_x))
end
reduced =reduce(vcat, unique(range_dict))
return (abs(minimum(reduced)) +maximum(reduced))
end# Part 2:functiondistress_beacon_frequency(x_limit::Int64=0, y_limit::Int64=4000000)
sensor_cord, beacon_cord =parse_input()
distance = [manhattan(sensor, beacon) +1for (sensor, beacon) inzip(sensor_cord, beacon_cord)]
for (sensor, dist) inzip(sensor_cord, distance)
for i in0:dist
p1 = [sensor[1] - dist + i, sensor[2] + i]
p2 = [sensor[1] - dist + i, sensor[2] - i]
p3 = [sensor[1] + dist - i, sensor[2] + i]
p4 = [sensor[1] + dist - i, sensor[2] - i]
distress_beacon_pos = [p1, p2, p3, p4]
for distress_beacon in distress_beacon_pos
ifmaximum(distress_beacon .>= x_limit) &&maximum(distress_beacon .<= y_limit)
ifall(x ->manhattan(distress_beacon, x[1]) >manhattan(x[1], x[2]), zip(sensor_cord, beacon_cord))
return distress_beacon[1] * y_limit + distress_beacon[2]
endendendendendend@timeno_beacon_position()
@timedistress_beacon_frequency()
Day 16:
using DataStructures
using RegularExpressions
using BenchmarkTools
functionparse_input()
valve_data =SortedDict{String,Dict}()
input =readlines("data_aoc/input_day16.txt")
line_regex =r"Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? (.*)"for line in input
matchd =match(line_regex, line).captures
valve_name = matchd[1]
flow_rate =parse(Int, matchd[2])
valve_data[valve_name] =Dict(
"flow_rate"=> flow_rate,
"tunnels"=>Set{String}()
)
tunnel_names =split(matchd[3], ", ")
for tunnel_name in tunnel_names
push!(valve_data[valve_name]["tunnels"], tunnel_name)
endendreturn valve_data
endfunctioncompute_distance()
valve_data =parse_input()
dist =Dict()
for valve inkeys(valve_data)
valve !="AA"&& (valve_data[valve]["flow_rate"] ==0) ?continue:nothing
dist[valve] =Dict("AA"=>0, valve =>0)
visited =Set([valve])
queue = Tuple[(0, valve)]
while!isempty(queue)
distance, position =popfirst!(queue)
for neighbor in valve_data[position]["tunnels"]
neighbor in visited ?continue:nothingpush!(visited, neighbor)
if (valve_data[neighbor]["flow_rate"]) !=0
dist[valve][neighbor] = distance +1endpush!(queue, (distance +1, neighbor))
endenddelete!(dist[valve], valve)
if valve !="AA"delete!(dist[valve], "AA")
endendreturn dist, valve_data
endfunctionday_16()
dist, valve_data =compute_distance()
nonempty_valves =collect(keys(filter(x -> x[1] !="AA", dist)))
# bitmasking
indicies =Dict([valve =>1<< i for (i, valve) inenumerate(nonempty_valves)])
functiondfs(valve, time, bitmask, max_pressure, cache)
cache[bitmask] =max(get(cache, bitmask, 0), max_pressure)
for (neighbor, dist_to) inpairs(dist[valve])
(indicies[neighbor] & bitmask !=0) ?continue:nothing
rem_time = time - dist_to -1
rem_time <=0?continue:nothingdfs(neighbor, rem_time, bitmask | indicies[neighbor], max_pressure + valve_data[neighbor]["flow_rate"] * rem_time, cache)
endreturn cache
end
part_1 =maximum(values(dfs("AA", 30, 0, 0, Dict{Int,Int}())))
my_second_visit =dfs("AA", 26, 0, 0, Dict{Int,Int}())
part_2 =maximum(pressure_1 + pressure_2 for (bitmask_1, pressure_1) in my_second_visit for (bitmask_2, pressure_2) in my_second_visit if (bitmask_1 & bitmask_2 ==0))
return part_1, part_2
end@time part_1, part_2 =day_16()
Day 17:
using DataStructures
functionmove_rock(rock::Vector{Tuple{Int64, Int64}}, coord::Tuple{Int64, Int64}, chamber::SortedSet)
for (x, y) in rock
x += coord[1]
y += coord[2]
if x <1|| y <1|| y >7|| (x, y) in chamber
return rock, falseendend
new_coords = [r .+ coord for r in rock]
return new_coords, trueendfunctionpyroclastic_flow(input_file::String)
jets = [Int(e) -61for e inread(input_file, String)]
jet_iter =1
rock_iter =1
chamber =SortedSet()
heights = []
seen =SortedDict()
rocks = [[(0, 0), (0, 1), (0, 2), (0, 3)],
[(1, 0), (0, 1), (1, 1), (2, 1), (1, 2)],
[(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)],
[(0, 0), (1, 0), (2, 0), (3, 0)],
[(0, 0), (0, 1), (1, 0), (1, 1)]]
for n in1:3000
max_y =isempty(chamber) ?0:last(chamber)[1]
rock_pos =map(x -> x .+ (max_y +4, 3), rocks[rock_iter])
rock_iter =mod1(rock_iter +1, length(rocks))
whiletrue
jet = jets[jet_iter]
jet_iter =mod1(jet_iter +1, length(jets))
rock_pos, ismoved =move_rock(rock_pos, (0, jet), chamber)
rock_pos, ismoved =move_rock(rock_pos, (-1, 0), chamber)
if!ismoved
union!(chamber, rock_pos)
breakendend
key_val = (rock_iter, jet_iter)
current_height =last(chamber)[1]
ifhaskey(seen, key_val)
last_rock, last_height = seen[key_val]
remaining_rocks =1_000_000_000_000- n
cycle_length = n - last_rock
height_increase = current_height - last_height
quotient, remainder =divrem(remaining_rocks, cycle_length)
if remainder ==0# println("found cycle with $n steps and $current_height height and $cycle_length length and $height_increase height and $quotient quotient")return heights[2022], current_height + height_increase * quotient, chamber
endelse
seen[key_val] = (n, current_height)
endpush!(heights, current_height)
endend
part_1, part_2, chamber =pyroclastic_flow("data_aoc/input_day17.txt");
@show part_1;
@show part_2;
functionprint_chamber(chamber)
max_y =isempty(chamber) ?0:last(chamber)[1]
for y in max_y:-1:4306# printing only the last 100print('|')
for x in1:7if (y, x) in chamber
print('#')
elseprint('.')
endendprintln('|')
endprintln("+-------+")
endprint_chamber(chamber)
Day 18:
functioncube_neighbors((x, y, z))
returnSet([(x +1, y, z), (x -1, y, z),
(x, y +1, z), (x, y -1, z),
(x, y, z +1), (x, y, z -1)])
endfunctionday_18(cubes, part_1=0, part_2=0)
# part 1for cube ∈ cubes
for neighbors ∈cube_neighbors(cube)
(neighbors ∉ cubes) ? [part_1 +=1] :nothingendend# part 2
min_Val =minimum(extrema(cubes)[1]) -1
max_val =maximum(extrema(cubes)[2]) +1
queue = [(min_Val, min_Val, min_Val)]
visited =Set()
while!isempty(queue)
cube =popfirst!(queue)
for neighbor ∈cube_neighbors(cube)
!(all([d >= min_Val && d <= max_val for d ∈ neighbor])) ?continue:nothing
neighbor ∈ visited ?continue:nothing
neighbor ∈ cubes ? [part_2 +=1] : [push!(visited, neighbor)
push!(queue, neighbor)]
endendreturn part_1, part_2
end
cubes =map(x ->Tuple(parse.(Int, x)), split.(split(read("data_aoc/input_day18.txt", String), "\n"), ","));
p1, p2 =day_18(cubes)