Skip to content

Instantly share code, notes, and snippets.

@f5-rahm
Created January 12, 2023 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save f5-rahm/37401dc41e5cc6e109dfec5e5ec0449f to your computer and use it in GitHub Desktop.
Save f5-rahm/37401dc41e5cc6e109dfec5e5ec0449f to your computer and use it in GitHub Desktop.
iRules Solution to Day 1 of the 2022 Advent of Code. Requires iFiles as named with the test and puzzle data (with final newline)
ltm rule aoc_day1 {
proc find_sum { snack_list } {
set calorie_sum 0
foreach snack [string map { \{ "" \} "" } $snack_list] {
set calorie_sum [expr {$calorie_sum + $snack}]
}
return $calorie_sum
}
proc find_max { elf_list } {
set max 0
foreach elf $elf_list {
if { $elf > $max } {
set max $elf
}
}
return $max
}
when HTTP_REQUEST priority 500 {
# Get and store test or puzzle data
if { [HTTP::uri] eq "/test" } {
set aoc_data [ifile get testdata]
} elseif { [HTTP::uri] eq "/puzzle" } {
set aoc_data [ifile get puzzledata]
} else {
HTTP::respond 406 content "Not an acceptable destination. You Lose, Good day, sir!"
return
}
# get data ready to iterate on
set aoc_data [split $aoc_data "\n"]
set aoc_data [split $aoc_data "{}"]
# iterate on the snack data
foreach snack $aoc_data {
if { $snack != {} } {
# append snacks list for current elf
lappend snacks $snack
} elseif { [info exists snacks] } {
# hit {}, tally up calories in last elf's snacks and append total to elf list
set elf_calories [call find_sum $snacks]
lappend elves $elf_calories
# unset snacks so new elf doesn't have last elf's data
unset -- snacks
}
}
# Solving Part 1
# find the elf with the most calories
set elf_max [call find_max $elves]
# Solving Part 2
# find the three elves with the most calories and summarize
set top_three [lrange [lsort -integer -decreasing $elves] 0 2]
set top_three [call find_sum $top_three]
# return the data
HTTP::respond 200 content "\n2022 Advent of Code - Day 1\n\n\tPart one: $elf_max\n\tPart two: $top_three\n\n"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment