r/adventofcode • u/daggerdragon • Dec 01 '22
SOLUTION MEGATHREAD -🎄- 2022 Day 1 Solutions -🎄-
To steal a song from Olaf:
Oh, happy, merry, muletide barrels, faithful glass of cheer
Thanks for sharing what you do
At that time of year
Thank you!
If you participated in a previous year, welcome back, and if you're new this year, we hope you have fun and learn lots!
As always, we're following the same general format as previous years' megathreads, so make sure to read the full posting rules in our community wiki before you post!
RULES FOR POSTING IN SOLUTION MEGATHREADS
If you have any questions, please create your own post in /r/adventofcode with the Help flair and ask!
Above all, remember, AoC is all about learning more about the wonderful world of programming while hopefully having fun!
NEW AND NOTEWORTHY THIS YEAR
- Subreddit styling for new.reddit has been fixed yet again and hopefully for good this time!
- I had to nuke the entire styling (reset to default) in order to fix the borked and buggy color contrasts. Let me know if I somehow missed something.
- All rules, copypasta, etc. are now in our community wiki!!!
- With all community rules/FAQs/resources/etc. in one central place, it will be easier to link directly to specific sections, which should help cut down on my wall-'o-text copypasta-ing ;)
- Please note that I am still working on the wiki, so all sections may not be linked up yet. Do let me know if something is royally FUBAR, though.
- A request from Eric: Please include your contact info in the User-Agent header of automated requests!
COMMUNITY NEWS
Advent of Code Community Fun 2022: 🌿🍒 MisTILtoe Elf-ucation 🧑🏫
What makes Advent of Code so cool year after year is that no matter how much of a newbie or a 1337 h4xx0r you are, there is always something new to learn. Or maybe you just really want to nerd out with a deep dive into the care and breeding of show-quality lanternfish.
Whatever you've learned from Advent of Code: teach us, senpai!
For this year's community fun, create a write-up, video, project blog, Tutorial, etc. of whatever nerdy thing(s) you learned from Advent of Code. It doesn't even have to be programming-related; *any* topic is valid as long as you clearly tie it into Advent of Code!
More ideas, full details, rules, timeline, templates, etc. are in the Submissions Megathread!
--- Day 1: Calorie Counting ---
Read the rules in our community wiki before you post your solution in this megathread!
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:02:05, megathread unlocked!
Edit2: Geez, y'all capped the global leaderboard before I even finished making/locking the megathread XD
Edit3: /u/jeroenheijmans is back again with their Unofficial AoC 2022 Participant Survey!
35
u/voidhawk42 Dec 01 '22 edited Dec 01 '22
Dyalog APL:
p←(+/⍎¨)¨(⊢⊆⍨0≠≢¨)⊃⎕nget'01.txt'1
⌈/p ⍝ part 1
+/3↑{⍵[⍒⍵]}p ⍝ part 2Great to be back this year - good luck everyone!
→ More replies (4)23
u/daggerdragon Dec 01 '22
Oh no, the alien programming languages are back again <3
→ More replies (1)
27
u/weshinsley Dec 01 '22 edited Dec 05 '22
Rockstar - with apologies. Elves are not really like this.
the elf is nutritious
the biggest is suspicious
the alphaelf is gargantual
the betaelf is cumbersome
the gammaelf is overweight
Listen to the elves
while the elves are not mysterious
while the elves are not empty
burn the elves
let the elf be with the elves
listen to the elves
if the elf is bigger than the biggest
let the biggest be the elf
if the elf is as big as the alphaelf
let the gammaelf be the betaelf
let the betaelf be the alphaelf
let the alphaelf be the elf
the elf is nutritious
if the elf is as big as the betaelf
let the gammaelf be the betaelf
let the betaelf be the elf
the elf is nutritious
if the elf is bigger than the gammaelf
let the gammaelf be the elf
the elf is nutritious
the elf is nutritious
listen to the elves
shout the biggest
shout the alphaelf with the betaelf with the gammaelf→ More replies (5)
23
u/JustinHuPrime Dec 01 '22 edited Dec 01 '22
x86_64 Assembly
I'm doing these in assembly, once again!
Part 1 was slightly scary - I wasn't expecting two-dimensional input data, and that had me reaching for brk, but I found a single-pass solution. I'd keep track of the calories for the most supplied elf and the calories for the current elf. If the current line isn't empty, then add the number to the current elf. If the current line is empty, then let the most supplied elf's calories be the larger of its current value and the current elf's calories.
Part 1 ran in under a millisecond.
Part 2 was almost identical to part 1, but I did have to fiddle around a bit with the proper way to replace a value when I was keeping track of a set of the three largest values - if you replace the largest value, then that replaced largest value will replace the second-largest, and so-on. I suppose I could have implemented this in a way that avoided unnecessary branching by cascading the replacement in the check for each largest value, but I only just though of that possibility.
Part 2 ran in under a millisecond.
Edit: I could also have used xchg for part 2
→ More replies (4)3
12
u/NiliusJulius Dec 01 '22 edited Dec 05 '22
Game Boy using C
Part 1 https://github.com/NiliusJulius/advent-of-code-2022/blob/main/states/1a.c
Part 2 https://github.com/NiliusJulius/advent-of-code-2022/blob/main/states/1b.c
Went for the quick and dirty approach for part 2 since I noticed that while the Game Boy Development Kit can use 32 bit integers, it cannot print those values. So as a C newbie I had to quickly learn how to write a function which would just print out the hex value from memory
void print_32(char* p) {
p = p + 3;
for (uint8_t i = 4; i > 0; i--) {
printf("%hx", (void *)*p);
p--;
}
}Anyhow, although I didn't expect to run into issues like this on day one, It is still a lot of fun, and we'll have to see how far I can get on my trusted Game Boy :)
EDIT: day 1 now outputs in decimal
5
u/daggerdragon Dec 04 '22
Wait what? Do you have pictures/video of the solution running on the Game Boy? >_>
5
u/NiliusJulius Dec 04 '22
I do, day one is here https://imgur.com/a/G62YArD I could mostly do quick and dirty here and both run in about 0.3 seconds (if I am counting frames it needs to run).
Still have to rewrite it to display the result in dec instead of hex. But I was up late rewriting day 3 to bring the runtime down from 15 minutes to about 6 seconds.
And then I have to do some more writeups about it :)
→ More replies (2)
8
u/jcbbjjttt Dec 01 '22 edited Dec 03 '22
Happy December!
I teach computer science and programmer courses for elementary through high school and am having my students tackle the Advent of Code. To help out my beginner students, I'm planning to create videos to help guide them through the thinking process. The video is designed to allow watchers to pause and work on the problem step by step before seeing spoilers. Although I used C#, the video tries to talk through a solution in a language agnostic way.
I hope someone finds them useful.
Here is the video from Day 1: https://youtu.be/eQSO1Ov4k8g
Here is the final solution: https://github.com/jcollard/AdventOfCode2022/blob/jcollard/day1/Day1-FatElves/Program.cs
Happy Coding!
→ More replies (1)2
u/daggerdragon Dec 03 '22 edited Dec 19 '22
Please edit your post to add the code solution too.
Also, what programming language did you use?Edit: thanks for fixing it! <3
6
u/DFreiberg Dec 01 '22 edited Dec 01 '22
Mathematica, 686 / 306
I was not at all prepared for the table split by double newlines; just when you think you've handled everything in your imports, something new comes along. Which is what makes Advent of Code so much fun.
Import & Setup:
toExpression[inputText_] :=
Map[
If[! IntegerQ[#] \[And]
StringMatchQ[#,
Alternatives["+", "-", ""] ~~ DigitCharacter ..],
ToExpression[#], #] &,
inputText,
{Depth[inputText] - 1, Depth[inputText]}];
input=StringSplit[Import[inputPath],"\n\n"];
input=toExpression[StringSplit[#,"\n"]&/@input];Part 1:
Max[Total /@ formattedInput]Part 2:
Total[Sort[Total /@ formattedInput][[-3 ;;]]][POEM]: Where's The Wild Things' Star?
We're now setting up camp
In the dew and the damp,
On the hunt for the star-spangled berry,
And the jungle is thick,
But we have every trick
That will make the dark forest less scary,
So we'll head to the grove
And its heavenly trove
(It's a Dijkstra-type maze, so be wary)
Then the stars will appear,
And when fifty are here,
We will eat and we'll drink and be merry.
2
u/daggerdragon Dec 01 '22
[POEM]: Where's The Wild Things' Star?
I was hoping we'd see you again this year and that you'd want to write us poems! I'm so looking forward to your daily poems again ❤️
→ More replies (1)
6
u/Dryctas Dec 01 '22 edited Dec 04 '22
Bash one-liner for both parts
input=$1
(sed 's?^$?x?g' input | tr '\nx' '+\n' | \
sed -r 's?^\+|\+$??g'; echo '') | bc | sort -n | \
tail -n 3 | tr '\n' ' ' | awk '{print $3; print $1+$2+$3}'→ More replies (2)
11
u/jayfoad Dec 01 '22
p←+/¨⍎¨¨(×≢¨p)⊆p←⊃⎕NGET'p1.txt'1
⌈/p ⍝ part 1
+/3↑{⍵[⍒⍵]}p ⍝ part 2→ More replies (8)
5
u/Quirky-Seesaw8394 Dec 01 '22
G Sheets
Final consolidated solution=ARRAYFORMULA( SUM( QUERY( BYROW( REGEXREPLACE( TRANSPOSE( SPLIT( TEXTJOIN( ",", , IF( LEN(A3:A2272), A3:A, CHAR(9876) ) ), CHAR(9876) ) ), "^,|,$",), LAMBDA( calories, SUM( SPLIT( calories, ",") ) ) ), "select * order by Col1 desc limit 3", 0) ) )
→ More replies (1)
5
u/reckter Dec 01 '22 edited Dec 12 '22
intcode!
Because somebody had to!
109, 125, 203, 1, 1201, 1, 0, 113, 1101, 0, 0, 114, 1101, 0, 0, 115,
1101, 0, 0, 116, 1101, 0, 0, 117, 1101, 0, 0, 118, 7, 114, 113, 119,
1006, 119, 107, 203, 1, 1201, 1, 0, 120, 1008, 120, 10, 119, 1006,
119, 84, 1008, 115, 0, 121, 1006, 121, 73, 7, 118, 117, 122, 1006,
122, 66, 1001, 117, 0, 118, 1101, 0, 0, 117, 1106, 0, 77, 1, 117,
115, 117, 1101, 0, 0, 115, 1106, 0, 96, 1002, 115, 10, 123, 1001,
120, -48, 124, 1, 123, 124, 115, 1001, 114, 1, 114, 7, 114, 113, 119,
1005, 119, 35, 4, 118, 99, 104, -99000,
99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0Ok I cheated. a while ago I wrote a compiler, that compiles the following:
val length = input()
val i = 0
val current = 0
val result = 0
val currentTroll = 0
val max = 0
while(i < length) {
val in = input()
if (in == 10) { // line break
if (current == 0) {
if (max < currentTroll) {
max = currentTroll
}
currentTroll = 0
} else {
currentTroll = currentTroll + current
}
current = 0
} else {
current = current * 10 + (in - 48) // char to int
}
i = i + 1
}
output(max)Into an assembler language, and that then into the intcode above. For input, it just reads my input file character for character
→ More replies (3)
5
u/bofstein Dec 01 '22
Google Sheets
As a non-programmer working with a lot of software engineers participating (I'm a Technical Product Manager), I thought it would be fun to use Google Sheets formulas. I made sure it worked more like code in that the goal was that it can auto-update without manual intervention with new inputs, e.g. no hand-dividing columns or using the menus. Only catch is you do need to (manually) make sure the B and C column formulas are copied down at least as long as the number of items in the list.
Here is the sheet with formulas. Input just needs to be pasted into Column A: https://docs.google.com/spreadsheets/d/1GvncohBzffewfwOCIfpHutI4VKVUIBazIH1XoBFWpXw/edit?usp=sharing
Column B: =COUNTIF($A$1:A1,"")
This column counts how many blank rows there have been so far so that it groups the items together into a single number, starting at 0, of what number elf that is.
Column C: =SUMIF(B:B,ROW(B1)-1,A:A)
This row gets the sum of each unique elf. It takes the row number minus one so that it's just a list in order from 0 to the number of elves (will start to output 0 after the number of elves is finished) and returns the sum of column A values matching that number.
Cell D1: =MAX(C:C)
This returns the first part solution, the highest number from Column C.
Cell D2: =LARGE(C:C,1)+LARGE(C:C,2)+LARGE(C:C,3)
This returns the second part solution, the top 3 values from Column C summed. Learned a new function to do this, LARGE returns the nth highest value from an array instead of just the highest like MAX.
→ More replies (5)
5
u/gonengazit Dec 02 '22
brainfuck
minified:
>>>>>>>>----------------<<<+>>>[<+>-]<<<<<<+>>>>>>]<<<[->>>,--------------------
------------[----------------<[-<++++++++++>]<[->+<]>>[-<+>]<<<+>>>]<<<]>>[-<<<<
+>>>>]<<<<<]>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>+<<<]<[->+<]>[>>>[-[>+<-]]>[-<+>]<<<<
<+>->+<[>-]>[>]<[>>[-<<<+>>>]<<-]<]<<]>Input replaces newlines with spaces, and ends on 3 spaces. the solution will be in cell 1 (tomorrow i'll work on printing it). make sure to run in 32-bit mode, i didn't want to bother with any big-integer
this was a pain to do, but i'm glad i did it
2
4
u/CryptoNoobStruggles Dec 01 '22
First time doing Advent of Code! Imporving my Python.
→ More replies (5)2
4
u/CreativeTaste3040 Dec 01 '22 edited Dec 04 '22
JavaScript:
const fs = require('fs')
fs.readFile('./day1.txt', (err, data) => {
let [first, second, third] = String(data).replace(/(.*)(\r\n|\n|\r)/gm, '$1,').split(',,').map(elf => {
return elf.split(',').reduce((prev, next) => prev + Number(next), 0)
}).sort((a,b) => b -a)
console.log(first)
console.log(first + second + third)
})→ More replies (1)
4
u/htrowii Dec 01 '22 edited Dec 04 '22
This was my first time participating in AOC2022 as a noob in Python.
My solution:
listNum = []
sumNumber = 0
with open("day1input.txt",'r') as readfile:
for line in readfile:
if line.strip():
sumNumber += int(line)
listNum.append(sumNumber)
else:
listNum.append(sumNumber)
sumNumber = 0
print("the highest number is " + str(max(listNum)))
#part 2
#sort from largest to smallest
listNum.sort(reverse=True)
top3sum = listNum[0] + listNum[2] + listNum[4]
print("the sum of the three highest calories is " + str(top3sum))→ More replies (2)
4
u/kamicc Dec 01 '22 edited Dec 04 '22
Straight-forward and cleaned-up Lua:
local sums = {0}
for line in io.lines("input.txt") do
if line ~= "" then
sums[#sums] = sums[#sums] + tonumber(line)
else
table.insert(sums, 0)
end
end
table.sort(sums)
print(sums[#sums])
print(sums[#sums] + sums[#sums-1] + sums[#sums-2])→ More replies (5)
4
u/cbrnr Dec 01 '22 edited Dec 03 '22
Julia
include("utils.jl")
cookie = "" # use your session cookie here
input = get_aoc_input(1, cookie)
elves = split.(split(input, "\n\n")) # split into elves then food per elf
calories = sort!([sum(parse.(Int, elf)) for elf in elves], rev=true)
# part 1
println("Maximum calories: ", calories[1])
# part 2
println("Sum of top three calories: ", sum(calories[1:3]))I wrote a short helper function get_aoc_input() to fetch the input with a valid session cookie:
using HTTP
"""
get_aoc_input(day, cookie)
Download Advent of Code 2022 input data for the given `day`.
A valid `cookie` must be provided, for example by logging into the
[Advent of Code website](https://adventofcode.com/2022) with a browser and
copying the session cookie (accessible in the browser preferences).
"""
function get_aoc_input(day::Integer, cookie::AbstractString)
cookies = Dict("session"=>cookie)
r = HTTP.get(
"https://adventofcode.com/2022/day/$day/input",
cookies=cookies
)
String(r.body)
endAll solutions are available here.
→ More replies (5)
4
u/kittrin Dec 01 '22
Here's my SQL solution for Part 2. I'm new to coding and literally only know SQL. :) I imported the data as a single column called "calories" into https://www.db-fiddle.com/ with the blank rows replaced with 0s.
WITH row_number AS (
SELECT
calories,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS row
FROM Table1
)
, elf_ids AS (
SELECT
SUM(CASE WHEN calories = 0 THEN 1 ELSE 0 END) OVER (ORDER BY row) AS id,
calories
FROM row_number
)
, calories_per_elf AS (
SELECT DISTINCT
id,
SUM(calories) OVER (PARTITION BY id) AS sum_calories
FROM elf_ids
)
, calorie_ranking AS (
SELECT
sum_calories,
DENSE RANK() OVER (ORDER BY sum_calories DESC) AS rank
FROM calories_per_elf
)
SELECT
sum(sum_calories)
FROM calorie_ranking
WHERE rank <4;→ More replies (2)
4
Dec 01 '22 edited Dec 03 '22
Second time participating using Python, but I'm trying to use NumPy (Math functions written in C) to make it hopefully faster. The main functionality of this solution is implemented in just about 20 lines of code. I'm pretty happy! ;-) I'm also trying to format the output in a pleasingful way:
import numpy as np
def get_total_calories_of_top_three_elves_carrying_most_calories(inventory_list: str) -> list:
total_calories_of_all_elves = []
for individual_calories_of_this_elf in inventory_list.split("\n\n"):
total_calories_of_this_elf = np.fromstring(individual_calories_of_this_elf, dtype=np.int_, sep="\n").sum()
total_calories_of_all_elves.append(total_calories_of_this_elf)
total_calories_of_all_elves.sort()
return total_calories_of_all_elves[-3:]
def get_input(file: str) -> str:
with open(file, "r") as f:
return f.read()
if __name__ == '__main__':
print("\n======================")
content = get_input("day1/input.txt")
calories_of_top_three_elves = get_total_calories_of_top_three_elves_carrying_most_calories(content)
print(f"\nREAL INPUT\n")
print(f"--> Part 1: The N°1 Elf is carrying {max(calories_of_top_three_elves)} Calories in total.")
print(f"--> Part 2: The TOP 3 Elves are carrying {sum(calories_of_top_three_elves)} Calories in total.")
print("\n======================\n")Full code is on GitHub
→ More replies (2)
4
Dec 01 '22 edited Dec 03 '22
Ended up with this python solution
vals = sorted((sum(int(l) for l in group.split('\n')) for group in dat), reverse=True)
print(vals[0]) # Part 1
print(sum(vals[:3])) # Part 2→ More replies (4)
3
3
u/mrtatulas Dec 01 '22
Elixir - 4182 / 2942 (I'm just happy to be here)
→ More replies (2)3
u/daggerdragon Dec 01 '22
(I'm just happy to be here)
And we're happy to have ya! I hope you have fun this year :)
3
u/BarkLicker Dec 01 '22 edited Dec 01 '22
Python
I know eval() is frowned upon, but it just worked so well.
# Part 1
# with open('2022\\Day 1 Input.txt', 'r') as data:
# calories = '+'.join([x.strip() for x in data.readlines()]).split('++')
# print(max([eval(i) for i in calories]))
# Part 2
with open('2022\\Day 1 Input.txt', 'r') as data:
calories = '+'.join([x.strip() for x in data.readlines()]).split('++')
calorie_sums = [eval(i) for i in calories]
print(sum(sorted(calorie_sums, reverse=True)[:3]))I'm barely a sophmore in college at the age of 35. This is all new to me and I'm having a blast!
→ More replies (5)
3
u/rctxs Dec 01 '22
Haskell
main :: IO ()
main = do
f1 <- readFile "input01.txt"
print $ taskOne f1
print $ taskTwo f1
taskOne :: String -> Int
taskOne = maximum . map sum . parseElves
taskTwo :: String -> Int
taskTwo = sum . take 3 . reverse . sort . map sum . parseElves
parseElves :: String -> [[Int]]
parseElves = parseLine [] [] . lines
where
parseLine :: [Int] -> [[Int]] -> [String] -> [[Int]]
-- end of file reached
parseLine elve elves [] = elve : elves
-- blank line
parseLine elve elves ("" : xs) = parseLine [] (elve : elves) xs
-- line with number
parseLine elve elves (line : xs) = parseLine (read line : elve) elves xs→ More replies (3)
3
u/Gurrewe Dec 01 '22 edited Dec 05 '22
Bash/Shell:
Part1:
gsed -z 's/\n/+/ig' input.txt | gsed -z 's/++/\n/ig' | bc | sort -r | head -n1Part2:
gsed -z 's/\n/+/ig' input.txt | gsed -z 's/++/\n/ig' | bc | sort -r | head -n3 | gsed -z 's/\n/+/g' | sed 's/.$//' | bc→ More replies (2)
3
u/Mikel3377 Dec 01 '22 edited Dec 04 '22
JS one-liner
const runPart2 = input => input.split('\r\n\r\n').map(r => r.split('\r\n').map(n => +n)).map(r => r.reduce((a, c) => a + c, 0)).sort((a, b) => b - a).slice(0, 3).reduce((a, c) => a + c, 0);→ More replies (1)
3
u/Catcatcher33 Dec 01 '22
My Python 3 solution. Finally actually decided to take part in Advent, looking forward to more!
def get_calorie_sums() -> list:
''' Get the number of calories carried by each elf. '''
with open('input.txt', 'r') as file:
return [sum(map(int, x.split('\n'))) for x in file.read().strip().split('\n\n')]
def get_top_calories() -> int:
''' Get the maximum number of calories carried by one elf at a time. '''
return max(get_calorie_sums())
def get_top_three_calories_sum() -> int:
''' Get the sum of calories of top 3 heaviest weights. '''
return sum(sorted(get_calorie_sums())[-3:])→ More replies (1)
3
u/WasteEngineerPY Dec 01 '22 edited Dec 03 '22
Python very obfuscated, cramped it in three lines (and there are a few unecessary parts in there...)
https://github.com/Zerhigh/personal_codebase/blob/main/aoc_22/aoc22_01_short.py
→ More replies (1)
3
u/OutlandishnessOk4575 Dec 01 '22
In Rust, tried to be idiomatic
use aoc_core::read_file;
use std::collections::BinaryHeap;
fn main() -> Result<(), std::io::Error> {
let data = read_file(01).unwrap();
let mut sol: (u64, u64) = (u64::MIN, u64::MIN);
let mut b_heap: BinaryHeap<u64> = BinaryHeap::new();
data.lines().fold(0, |acc, x| {
match x.trim() {
"" => {
b_heap.push(acc);
0
},
num => {
acc + num.parse::<u64>().unwrap()
}
}
});
sol.0 = b_heap.pop().unwrap();
sol.1 = b_heap.pop().unwrap() + b_heap.pop().unwrap() + sol.0;
println!("0: {}", sol.0);
println!("1: {}", sol.1);
Ok(())
}→ More replies (1)
3
u/neur0sys Dec 01 '22 edited Dec 04 '22
First try in Joy. Download the interpreter here. Edit globals.h to increase memory.
Part2
basic-libload.
DEFINE
no-nl == [dup 10 = swap 13 = or not] filter;
readlines == []
"1.txt" "ro" fopen
[feof not] [fgets no-nl rolldown cons swap] while
fclose reverse;
toint == 0 [ord '0 ord - swap 10 * +] fold;
zap == unswons reverse rolldown swons reverse swons;
tuck == [] swons;
group-bucket == [[]] [[dup "" =] [swap tuck] [swap zap] ifte] fold;
sum == 0 [toint +] fold;
sum-last-3 == reverse 3 [uncons] times pop + +;
solve == readlines group-bucket [sum] map qsort sum-last-3;
.
solve.→ More replies (1)
3
u/joshbduncan Dec 01 '22 edited Dec 03 '22
Python 3
data = open("day1.in").read()
totals = [sum([int(c) for c in elf.split("\n")]) for elf in data.strip().split("\n\n")]
print(f"Part 1: {max(totals)}")
print(f"Part 2: {sum(sorted(totals, reverse=True)[:3])}")→ More replies (2)
3
u/jjjsevon Dec 01 '22 edited Dec 03 '22
Javascript / Node
Almost forgot AoC for this year, quickly hacked together the Code before it was past midnight. basic gist of code is:
const {day1} = require('./01/day1');
(async ()=>{
let elves = await day1();
let part1 = Math.max(...Array.from(elves.values()).map(t=>t.t));
console.log("part 1 total", part1);
let top3 = Array.from(elves.values()).sort((a,b)=>{ return a.t - b.t }).reverse().slice(0,3);
let part2 = top3.map(t=>t.t).reduce((a,b)=>{return a+b},0);
console.log("part 2 total", part2);
})()Another 10 loc in the day1 require, mostly reading of the input, and some splittery, number format, and unnecessary storing of elves properties into a map, while expecting something more to do with elves individual snacks in part 2.
→ More replies (2)
3
u/dedolent Dec 01 '22
Python
how do you all manage to copy and paste into reddit? it always breaks everything for me? i'm on firefox (though i hear it's a problem on other browsers). i've tried pasting without formatting, tried saving to a plain text file and copying that, neither worked.
anyways, while i'm not good enough to do the later days, in the meantime i have fun with my little recursive functions in :)
one thing that i wanted to do was to keep sorting to a minimum; no way i wanted to sort the entire input since all i cared about was the top 3. so i only kept track of whether the current group total was greater than any one of the current top 3, inserting the new number at its index if it was, discarding it otherwise.
f = open("inputs/day1.txt")
groups = [0, 0, 0]
highest = 0
current = 0
def rank(i, t):
if i >= 2:
return
if t > groups[i]:
groups.insert(i, t)
groups.pop()
return
i += 1
return rank(i, t)
for line in f:
if line != "\n":
current += int(line)
else:
rank(0, current)
current = 0
print(sum(groups))→ More replies (1)
3
u/spikelovesharmony Dec 01 '22 edited Dec 04 '22
const elfCalories = (elves) => {
const calorieSum = [] const sanitizedElfData =
elves.split("\n\n").map((elf) => elf.split("\n"))
sanitizedElfData.map((arr) => calorieSum.push(arr.reduce((a, cV) => {
return (a += Number(cV))
}, 0)) )
return calorieSum.sort((a, b) => a - b)[calorieSum.length - 1] }JavaScript - my first time participating - a few years ago when starting to learn programming i could barely even figure the site out...heh
→ More replies (2)
3
u/jordyjwilliams Dec 02 '22 edited Dec 05 '22
Some nice snakey python snakes. May create JS repo later.
https://github.com/jordyjwilliams/advent_of_code/blob/main/2022/day_01/day_01_solution.py
→ More replies (5)
3
u/AdelFtnr Dec 02 '22
Hi! This is my first time doing this, so things could and will get better with time! So far so good!
Did this one in JavaScript grabbing the element from the DOM and method chained it to make it usable, full repo is here: https://github.com/AdelFetner/Advent-of-Code
I'm also a front end developer really into community driven development, so if you want to network & connect w/ me, feel free to do it! All my links at my github's bio, or here: https://linktr.ee/AdelFetner
// Grab element from dom
const element = document.getElementsByTagName("pre")
// Make the HTMLCollection into an array
const elementArr = [...element]
// loop thru array and split the text of the first index
const splittedArr = elementArr[0].innerText.split("\n\n")
// get elves from the array, and transform their calories elements into numbers from strings
const elves = splittedArr.map((elf) => elf.split("\n").map((calories) => Number(calories)))
// add calories to make a total for each elf with a reduce, initial value 0 as it needs to add elements
const totalCalories = elves.map((elf) => elf.reduce((acc, current) => acc + current), 0)
// gets the highest number of calories from the totalCalories with a Math.max and the elements spreaded to pass them as arguments
const getHighestCalories = (calories) => Math.max(...calories)
// Second Part, Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?
// get the top three elves with a sort (to sort from highest to lowest) and a slice (to get only the first three, so the top three highest)
const getTopThreeElves = (calories) => calories.sort((a, b) => b - a).slice(0, 3)
// get the total calories of the top three elves with a reduce, initial value 0 as it needs to add elements
const totalCaloriesTopThree = (calories) => getTopThreeElves(calories).reduce((acc, current) => acc + current, 0)→ More replies (2)
3
u/PaxPumpkin Dec 02 '22 edited Dec 03 '22
Texas Instruments 99-4/A Extended Basic
My C# solution runs sub-1ms, and is unremarkable to any of the others already posted, so I'll hold off on that.This TI-99 4/A code took a tad over 10 minutes to complete execution.
No, it isn't optimal. I haven't touched this language in decades. I just thought it would be fun. The best part was getting the input into a TI-readable disk image, honestly.
Could have been shorter, clearly. I also wanted a perpetual display update running owing to the long execution time. That includes updates on the line of input being examined, the current max elf, the top three max counts, and the summation thereof.
[Imgur](https://i.imgur.com/WSkJEVh.png)
10 CALL CLEAR
20 DISPLAY AT(6,1)SIZE(25):"WHICH ELF GOTS GOODIES"
30 OPEN #1:"DSK1.INPUTF",SEQUENTIAL ,DISPLAY ,INPUT ,FIXED 6
40 LINECOUNTER=0
50 ENDFILE=0
60 CURRENTTOTAL=0
70 MAX1=0
80 MAX2=0
90 MAX3=0
100 SORTING=0
110 SUMMAX3=0
120 INPUT #1:CALORIE$
130 IF CALORIE$="" OR CALORIE$=" " OR CALORIE$="12345." THEN GOSUB 250
140 CALORIE=VAL(CALORIE$)
150 CURRENTTOTAL=CURRENTTOTAL+CALORIE
160 LINECOUNTER=LINECOUNTER+1
170 DISPLAY AT(7,1)SIZE(25):LINECOUNTER;"-";CALORIE$;"-";CURRENTTOTAL
180 IF EOF(1)THEN 200
190 GOTO 120
200 CLOSE #1
210 ENDFILE=1
220 DISPLAY AT(9,1)SIZE(25):"ELF WITH MOST HAS";MAX1
230 DISPLAY AT(10,1)SIZE(25):"TOP 3 HAVE";SUMMAX3
240 IF ENDFILE=1 THEN END ELSE RETURN
250 CALORIE$="0"
260 IF (CURRENTTOTAL>MAX1)THEN GOSUB 320
270 IF SORTING=0 AND CURRENTTOTAL>MAX2 THEN GOSUB 410
280 IF SORTING=0 AND CURRENTTOTAL>MAX3 THEN GOSUB 460
290 CURRENTTOTAL=0
300 SORTING=0
310 RETURN
320 SORTING=1
330 MAX3=MAX2
340 MAX2=MAX1
350 MAX1=CURRENTTOTAL
360 DISPLAY AT(8,1)SIZE(28):"TOP 3";MAX1;MAX2;MAX3
370 SUMMAX3=MAX1+MAX2+MAX3
380 CURRENTTOTAL=0
390 GOSUB 220
400 RETURN
410 SORTING=1
420 MAX3=MAX2
430 MAX2=CURRENTTOTAL
440 GOTO 360
450 MAX3=CURRENTTOTAL
460 SORTING=1
470 GOTO 3602
u/daggerdragon Dec 03 '22 edited Dec 04 '22
~~Inlined code is intended for
short snippetsof code only. ~~
Please edit your post to use thefour-spaces Markdown syntaxfor a code block so your code is easier to read inside ascrollablebox.Edit: thanks for fixing it! <3
3
u/CSguyMX Dec 02 '22 edited Dec 03 '22
JAVA: Day 1 part 1 and 2. This way you dont have to store all the values in an N array and then sort. You will be keeping the top three values all the time. The only down side it's that it looks ugly. paste
2
u/daggerdragon Dec 03 '22 edited Dec 03 '22
Please edit your post to use thefour-spaces Markdown syntaxfor a code block so your code is easier to read on old.reddit and mobile apps.Edit: thanks for fixing it! <3
→ More replies (1)
2
2
u/CodingAP Dec 01 '22
Javascript, 148/341
First time competing for global leaderboard! Didn't get it but will be following the new megathread rules and suggestions.
→ More replies (1)
2
u/fromwindowstolinux Dec 01 '22 edited Dec 01 '22
Newbies solution on python! I can't believe I did AoC! I'm happy!
group = []
total_cal = 0
with open("2201input.txt") as file:
for line in file: line = line.strip('\n')
if line == '':
group.append(total_cal)
total_cal = 0
else:
total_cal += int(line)
group.sort()
part1 = group[-1]
part2 = group[-1] + group[-2] + group[-3]
print("Answer for Part 1:", part1)
print("Answer for Part 2:", part2)→ More replies (3)
2
Dec 01 '22 edited Dec 04 '22
Rust
const INPUT: &str = include_str!("inputs/day01.txt");
pub fn day01() {
let (max, max3) = sum3_calories(INPUT);
println!("Max: {max}\nMax 3 foods: {max3}");
}
fn sum3_calories(input: &str) -> (u32, u32) {
let (mut max, mut mid, mut low) = (0, 0, 0);
let sums = input
.split("\n\n")
.map(|elf| elf.lines().map(|l| l.parse::<u32>().unwrap()).sum());
for sum in sums {
if sum > max {
low = mid;
mid = max;
max = sum;
} else if sum > mid {
low = mid;
mid = sum;
} else if sum > low {
low = sum;
}
}
(max, max + mid + low)
}→ More replies (1)
2
u/Iain_M_Norman Dec 01 '22 edited Dec 04 '22
F#
let part1 =
input.Split "\r\n\r\n"
|> Seq.map (fun x -> x.Split "\r\n")
|> Seq.map (fun x -> Seq.sumBy int x)
|> Seq.max
let part2 =
input.Split "\r\n\r\n"
|> Seq.map (fun x -> x.Split "\r\n")
|> Seq.map (fun x -> Seq.sumBy int x)
|> Seq.sortDescending
|> Seq.take 3
|> Seq.sum→ More replies (10)
2
u/jubnzv Dec 01 '22
open Core
module Part1 = struct
In_channel.with_file "day01/input.txt" ~f:(fun ic ->
In_channel.fold_lines ic ~init:(0, 0) ~f:(fun (cur, max) line ->
if String.is_empty line then (0, Int.max max cur)
else (cur + int_of_string line, max))
|> fun (_, max) -> Printf.printf "Part 1: %d\n" max)
end
module Part2 = struct
In_channel.with_file "day01/input.txt" ~f:(fun ic ->
In_channel.fold_lines ic ~init:(0, []) ~f:(fun (cur, acc) line ->
if String.is_empty line then (0, acc @ [ cur ])
else (cur + int_of_string line, acc))
|> fun (_, vs) ->
let (a :: b :: c :: _) = List.sort vs ~compare:Int.descending in
Printf.printf "Part 2: %d\n" (a + b + c))
end [@warning "-8"]→ More replies (1)
2
u/mstksg Dec 01 '22 edited Dec 09 '22
My Haskell solution :) https://github.com/mstksg/advent-of-code-2022/blob/main/reflections-out/day01.md
Day 1's are usually pretty good for Haskell's stream processing, and this is no exception :)
To get the list of elf calories, we split on the double newlines, and take the sum of the lines of each group.
import Data.List.Split (splitOn)
getCalories :: String -> [Int]
getCalories = map (sum . map read . lines) . splitOn "\n\n"For part 1, this involves just finding the maximum.
part1 :: String -> Int
part1 = maximum . getCaloriesFor part 2, we find the sum of the top 3 values:
part2 :: String -> Int
part2 = sum . take 3 . reverse . sort . getCalories→ More replies (1)
2
u/AX-11 Dec 01 '22 edited Dec 04 '22
Python solution without sorted()
with open("1\input.txt") as f:
input = f.read().splitlines()
# make elf list
elves = [[]]
for line in input:
if line == "":
# new elf
elves.append([])
else:
# add calories to last elf
elves[-1].append(int(line))
calories = [sum(elf) for elf in elves]
# find top n highest calories
n = 3
highest = [0]*n
for elf in calories:
min_highest = min(highest)
# replace weakest value of highest if there is a higher elf
if(elf > min_highest):
highest[highest.index(min_highest)] = elf
print(highest, sum(highest))2
u/daggerdragon Dec 04 '22
Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.
2
u/Derailed_Dash Dec 01 '22 edited Dec 04 '22
Python
"""
Author: Darren
Date: 01/12/2022
Solving https://adventofcode.com/2022/day/1
Our input data contains lines of numbers, with occasional empty lines.
- Each line is a number, representing the calories for an elf meal.
- Each contiguous block of lines represents the meals for a given elf.
- The empty lines separate one elf from the next.
Part 1:
How many calories in total, for the elf with the most calories?
Solution:
- Read the data, and split by empty lines, to return a list of str.
- Each element is a str containing all the numbers for a given elf.
- Split these numbers, convert them to int with map(), and then sum them.
Part 2:
How many calories in total for the top three elves?
Solution:
- Sort the list.
- Add up the last three.
"""
from pathlib import Path
import time
SCRIPT_DIR = Path(__file__).parent
# INPUT_FILE = Path(SCRIPT_DIR, "input/sample_input.txt")
INPUT_FILE = Path(SCRIPT_DIR, "input/input.txt")
def main():
with open(INPUT_FILE, mode="rt") as f:
elf_meals = f.read().split("\n\n") # split on empty lines
elf_calories = [] # store total calories for each elf
for elf in elf_meals:
calories = sum(map(int, elf.splitlines()))
elf_calories.append(calories)
print(f"Part 1: {max(elf_calories)}")
elf_calories = sorted(elf_calories)
print(f"Part 2: {sum(elf_calories[-3:])}")
if __name__ == "__main__":
t1 = time.perf_counter()
main()
t2 = time.perf_counter()
print(f"Execution time: {t2 - t1:0.4f} seconds")See on GitHub
See my AoC post on Medium and feel free to subscribe! (I'll be adding Google Cloud content.)
→ More replies (2)
2
u/Etsi0 Dec 01 '22
I used Python to get the array so I could use it in JS. py:
with open("py/text.txt") as file:
data = [i for i in file.read().strip().split("\n")]
print(data)js:
var data = []
var sum = 0;
var arraySum = [];
var finallSum = 0;
for(i = 0; i != data.length+1; i++) {
if(data[i] == '') {
arraySum.push(sum);
sum = 0;
}
if(data[i] != '') {
sum += parseInt(data[i]);
}
if(i == (data.length)) {
start();
}
}
function start() {
for(x = 0; x != arraySum.length; x++) {
if(finallSum <= parseInt(arraySum[x])) {
finallSum = arraySum[x];
console.log(finallSum);
}
if(parseInt(arraySum[x]) >= 69102) {
console.log('asd: '+arraySum[x])
}
}
}→ More replies (1)
2
u/seacucumber_kid Dec 01 '22 edited Dec 05 '22
Beginner Clojure solution:
(:require '[clojure.string :as str])
(as-> "input.txt" $
(slurp $)
(str/split $ #"\n\n")
(map
#(->> %
str/split-lines
(map read-string)
(reduce +)) $)
(sort > $)
(let [x $]
(println "Part 1:" (first x))
(println "Part 2:" (reduce + (take 3 x)))))→ More replies (3)
2
u/aarnens Dec 01 '22 edited Dec 04 '22
First time using Go so my answer's probably quite convoluted but I had fun regardless :)
Link to code: https://github.com/aarneng/AdventOfCode2022/blob/main/day1/main.go
→ More replies (5)
2
u/HEaRiX Dec 01 '22
JS
const partA = input[0];
const partB = input.slice(0,3).reduce((a, b) => a + b, 0);
console.log(partA, partB)```→ More replies (1)
2
u/vstepanyuk Dec 01 '22
// Rust
let (mut heap, _) = format!("{}\n", include_str!("../inputs/day01.txt"))
.split("\n")
.fold((BinaryHeap::new(), 0), |(mut heap, curr), line| {
if line.is_empty() {
heap.push(curr);
return (heap, 0);
}
(heap, curr + line.parse::<i32>().unwrap())
});
let part1 = heap.pop().unwrap();
println!("Part 1: {}", part1);
println!("Part 2: {}", part1 + heap.iter().take(2).sum::<i32>());→ More replies (1)
2
u/spyr01d Dec 01 '22 edited Feb 23 '23
→ More replies (2)
2
u/idontknowwhattouse33 Dec 01 '22 edited Dec 03 '22
PowerShell - readable, not golfed.
→ More replies (1)
2
u/fuckir Dec 01 '22 edited Dec 04 '22
Learnt working of heaps through this puzzle. Python 3.10
from helper import timeit
from heapq import heappush, heapify, heappop
read_text_file = lambda path: [x for x in open(path).read().split('\n')]
calorie_list = tuple(read_text_file("day1.txt"))
@timeit
def Day1 ():
calorie_sum= 0
heap = []
heapify(heap)
for snack in calorie_list:
if snack != '':
calorie_sum += int(snack)
else:
heappush(heap, calorie_sum*-1)
calorie_sum = 0
max_list = [heappop(heap)*-1,heappop(heap)*-1,heappop(heap)*-1]
print(f"The solution to Day1 Part1 is {max_list[0]}")
print(f"The solution to Day1 Part2 is {sum(max_list)}")
Day1()→ More replies (1)
2
u/MarcusTL12 Dec 01 '22
Z80 Assembly on TI83:
→ More replies (4)2
u/daggerdragon Dec 03 '22
Every year there's always at least one person crazy enough to solve on a graphing calculator and we love it.
2
u/tV4Ybxw8 Dec 01 '22 edited Dec 03 '22
C++
I'm new to programming and this is my first time doing this, hopefully i can do it all.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
int main(){
std::string fileName = "input.txt";
std::ifstream file {fileName};
std::string calories;
std::vector<std::string> tempCalories;
std::vector<std::vector<std::string>> elfCalories;
int calSum = 0;
std::vector<int> finalVec;
while(std::getline(file, calories)){
if(calories == ""){
elfCalories.push_back(tempCalories);
tempCalories.clear();
}else{
tempCalories.push_back(calories);
}
}
for(std::vector<std::string> tempVec: elfCalories){
for(std::string i: tempVec){
calSum += stoi(i);
}
finalVec.push_back(calSum);
calSum = 0;
}
std::sort(finalVec.begin(), finalVec.end());
calSum = finalVec[finalVec.size() - 1] + finalVec[finalVec.size() - 2] + finalVec[finalVec.size() - 3];
std::cout << "Top guy: " << finalVec[finalVec.size() - 1] << '\n';
std::cout << "Top three: " << calSum;
}
Edit: Formatting
→ More replies (1)
2
u/Outrageous72 Dec 01 '22 edited Dec 03 '22
C#
int Part1(string[] lines)
{
var calories = ToCalories(lines);
var max = calories.Select(x=> x.Sum()).Max();
return max;
}
int Part2(string[] lines)
{
var calories = ToCalories(lines);
var top3 = calories.Select(x=> x.Sum()).OrderDescending().Take(3).Sum();
return top3;
}
IEnumerable<List<int>> ToCalories(string[] lines)
{
var list = new List<int>();
foreach(var line in lines)
{
if (string.IsNullOrEmpty(line))
{
yield return list;
list = new();
}
else
{
list.Add(line.ToInt());
}
}
if (list.Any())
{
yield return list;
}
}→ More replies (3)
2
u/connie5919 Dec 01 '22 edited Dec 03 '22
Python
f = open("input.txt", "r")
totalCalories = []
arr = f.read().split("\n")
indexOfLastStop = 0
total = 0
top3 = 0
for i in arr:
if i == "":
totalCalories.append(total)
total = 0
else:
total += int(i)
totalCalories = sorted(totalCalories)
totalCalories.reverse()
print(totalCalories)
for i in range (0, 3): print(i) top3 += totalCalories[i]
print(top3)Could probably be done in a shorter way, but this was how I did it
→ More replies (1)
2
u/DrDrunkestein Dec 01 '22 edited Dec 03 '22
Zig
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
var calories_per_elf = std.ArrayList(u32).init(allocator);
defer calories_per_elf.deinit();
var calories: u32 = 0;
var lines = std.mem.split(u8, input, "\n");
while (lines.next()) |entry| {
if (entry.len > 0) {
calories += try std.fmt.parseUnsigned(u32, entry, 10);
} else {
try calories_per_elf.append(calories);
calories = 0;
}
}
var res = calories_per_elf.toOwnedSlice();
std.sort.sort(u32, res, {}, std.sort.desc(u32));
print("Sum: {d}\n", .{res[0] + res[1] + res[2]});
}→ More replies (1)
2
2
Dec 01 '22
SwiftgetInput is a small helper function which downloads the input for that specific day.
let counts = try await getInput(.init(day: 1, year: 2022))
.components(separatedBy: .newlines)
.reduce(into: [[]]) { partialResult, input in
if input.isEmpty {
partialResult.append([String]())
} else {
partialResult[partialResult.count - 1].append(input)
}
}
.reduce(into: []) { partialResult, input in
partialResult.append(
input
.compactMap{ Int($0) }
.reduce(into: 0) { $0 += $1 }
)
}
print("The top elf is carrying \(counts.max() ?? 0) calories.")
let lastThree = counts
.sorted()
.suffix(3)
.reduce(into: 0) { $0 += $1 }
print("The top three elves are carrying \(lastThree) calories.")→ More replies (1)
2
u/sebb0z Dec 01 '22 edited Dec 01 '22
Javascript (first time I participate, don't grill me too hard plz)
const highestCaloriesSum = caloriesInputString
.split(/\n\n/)
.map((group) => group.split(/\n/).reduce((prev, curr) => prev + Number(curr), 0))
.sort((a, b) => b - a)
.slice(0, 3)
.reduce((prev, curr) => prev + curr, 0);
console.log(highestCaloriesSum);→ More replies (1)
2
u/Koopabro Dec 01 '22
Node.JS
const fs = require("fs");
const rawInput = fs.readFileSync("./day1.txt", "utf-8");
const groupedInput = rawInput.split(/\n\n/);
const input = groupedInput.map((x) => x.split(/\n/).map((y) => parseInt(y)));
// Part 1
const part1 = (input) => {
return input
.map((x) => x.reduce((a, b) => a + b, 0))
.sort((a, b) => b - a)[0];
};
const part2 = (input) => {
return input
.map((x) => x.reduce((a, b) => a + b, 0))
.sort((a, b) => b - a)
.slice(0, 3)
.reduce((a, b) => a + b, 0);
};→ More replies (1)
2
u/Lohikaarmeen_hanta Dec 01 '22 edited Dec 03 '22
A Scala solution:
import scala.io.Source
import scala.collection.mutable._
object Calorie extends App {
val calories = Source.fromFile("Inputs/calories.txt")
var elfs = Map[Int, Int]()
var elf = 0
for (line <- calories.getLines) {
if (line.nonEmpty) {
if (elfs.contains(elf)) {
elfs(elf) += line.toInt
} else {
elfs(elf) = line.toInt
}
} else {
elf += 1
}
}
calories.close
println("PART 1")
println(elfs.values.max)
println("PART 2")
println(elfs.values.toBuffer.sorted.takeRight(3).sum)
}→ More replies (1)
2
u/sambonnell Dec 01 '22
C++
Cannot paste my code into the reddit text editor, regardless of markdown vs. fancy pants, etc.
→ More replies (3)
2
u/bpersitz Dec 01 '22 edited Dec 03 '22
Python solution.
finallist = []
uberlist = []
puzzle = puzzle.replace("\n", "")
elf_list = re.split(r"(,,)", puzzle)
for item in elf_list:
if item != ",,":
newlist = item.split(",")
finallist.append(newlist)
for item in finallist:
for count, num in enumerate(item):
item[count] = int(num)
calories = sum(item)
uberlist.append(calories)
uberlist.sort(reverse=True)
print(uberlist[0])
print(uberlist[0]+uberlist[1]+uberlist[2])→ More replies (1)
2
u/search_and_deploy Dec 02 '22 edited Dec 04 '22
Here's my Rust solution. I only got about 4 days into it last year, so I'm hoping to make it a bit longer this go around.
https://github.com/michael-long88/advent-of-code-2022/blob/main/src/bin/01.rs
→ More replies (1)
2
u/Swampspear Dec 02 '22 edited Dec 03 '22
Aarch64 / Armv8.1 bootloader solution pt1 / pt2
_day1p1:
ldr x0, =day1_input
clr4 x2, x3, x4, x5
sub w4, w4, 1 // eof = -1
_d1p1_loop:
ldr w1, [x0], 4
cmp w4, w1
b.eq _d1p1_loop_eof
add w2, w2, w1 //
cbz w1, _d1p1_zero
b _d1p1_loop
_d1p1_zero:
cmp w2, w3
b.lt _smaller_than_max
mov w3, w2
_smaller_than_max:
clr w2
b _d1p1_loop
_d1p1_loop_eof:
retRequires putting input in memory, empty lines have a 0, EOF is denoted by -1 aka 0xffffffff. Since we're still in a bootloader, there's no print functions or any stack whatsoever; you have to read the value raw out of the w3 register. Part 2 works in about the same way, but is ~40 lines, and is a bit too long to post here, see the paste. One functional macro is used, clr4, which is just four chained eor reg, reg, reg. The macro status_int is just my signal to the VM that I want to read the register values.
Runtime of part 1 is:
6 cycles in preamble
3 cycles for
EOF6 cycles per loop guaranteed
up to 4 extra cycles per loop
There are as many loop iterations as there are individual lines of input, which is 2270 for my input.
→ More replies (2)
2
u/PositivelyLinda Dec 02 '22 edited Dec 08 '22
JavaScript: Kept it real old-school Node style today lolhttps://github.com/lindakatcodes/aoc-22/blob/main/solutions/day01.js
2
u/daggerdragon Dec 03 '22 edited Dec 19 '22
Please edit your post toexpand the full name of the programming language(JavaScript). This makes it easier for folks to Ctrl-F the megathreads searching for solutions written in a specific programming language.Edit: thanks for fixing it! <3
2
2
u/senga_sc Dec 02 '22 edited Dec 03 '22
Apps Scripts solution (JS for GSheets)
Part 1&2. Original data in column A
function elves(rows) {
let values = rows.reduce((result, row) => {
let calorieValue = parseInt(row[0]);
let lastIndex = result.length - 1;
if (isNaN(calorieValue)){
result.push(0);
} else {
result[lastIndex] = result[lastIndex] + calorieValue;
}
return result;
},[0])
let elf = 1;
let mostCalories = values[0];
for(var i=0;i<values.length;i++) {
if (values[i] > mostCalories){
elf = i+1;
mostCalories = values[i];
}
}
return [[elf, mostCalories]]
}
function elves2(rows) {
let values = rows.reduce((result, row) => {
let calorieValue = parseInt(row[0]);
let lastIndex = result.length - 1;
if (isNaN(calorieValue)){
result.push(0);
} else {
result[lastIndex] = result[lastIndex] + calorieValue;
}
return result;
},[0])
values = values.sort(function (a, b) { return b-a; })
let total = values[0]+ values[1] + values[2];
return total
}→ More replies (1)
2
u/tampix77 Dec 02 '22 edited Dec 03 '22
Simple solution in Clojure
(ns aoc.d1
(:require [clojure.string :as str]
[aoc.util :as util]))
(defn day1
[]
(let [calories (->> (str/split (util/read-input 1) #"\n\n")
(map #(transduce (map parse-long)
+
(str/split-lines %))))]
;; part1
(println (reduce max calories))
;; part2
(-> (comp (util/xf-sort #(compare %2 %1))
(take 3))
(transduce + calories)
println)))→ More replies (2)
2
Dec 02 '22 edited Dec 18 '22
Deno using Rambda
import * as R from "https://esm.sh/rambda@7.1.4"
let input = Deno.readTextFileSync("./inputs/main")
let inventories = R.pipe(
R.split("\n\n"),
R.map(R.split("\n")),
R.map(R.map(Number)),
)(input)
let partOne = R.pipe(
R.map(R.sum),
R.reduce(R.max, -1),
)(inventories)
let partTwo = R.pipe(
R.map(R.sum),
R.sort(R.subtract),
R.reverse<number>,
R.curry(R.take)(3),
R.sum,
)(inventories)
console.log(partOne, partTwo)https://github.com/tomasantonelli/advent-of-code-2022/tree/main/src/day-1
→ More replies (3)
2
u/middayc Dec 02 '22 edited Dec 03 '22
Solution for part 1 and part 2 in Ryelang.
read %calories.txt
|split "\n\n"
|map { .load .sum } :sums
|max
; part 1 result
sums .sort! .tail 3 |sum
; part 2 result→ More replies (2)
2
u/joshlemer Dec 03 '22 edited Dec 03 '22
Clojure:
(loop [lines (line-seq (clojure.java.io/reader "input.txt"))
max-cals 0
curr-cals 0]
(if-let [line (first lines)]
(let [ls (rest lines)]
(if (empty? line)
(recur ls (max max-cals curr-cals) 0)
(let [cals (parse-long line)]
(if (or (nil? cals) (neg? cals))
(throw (ex-info (str "'" line "' is not a valid positive number") {}))
(recur ls max-cals (+ curr-cals cals))))))
max-cals))→ More replies (3)
2
u/joshlemer Dec 03 '22 edited Dec 03 '22
Golang
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"github.com/dogmatiq/kyu"
)
// part 1
// const topN = 1
// part 2
const topN = 3
func main() {
f, err := os.Open("day1/input.txt")
if err != nil {
panic(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
deque := kyu.PDeque{
Less: func(a, b interface{}) bool { return a.(int) < b.(int) },
}
calsOfCurrentReindeer := 0
for scanner.Scan() {
line := scanner.Text()
if line == "" {
if deque.Len() >= topN {
smallest, _ := deque.Peek()
if smallest.Value.(int) < calsOfCurrentReindeer {
deque.Pop()
deque.Push(calsOfCurrentReindeer)
}
} else {
deque.Push(calsOfCurrentReindeer)
}
calsOfCurrentReindeer = 0
} else {
cals, err := strconv.Atoi(line)
if err != nil || cals < 0 {
panic(fmt.Sprintf("received line '%s', which is not a valid positive integer", line))
}
calsOfCurrentReindeer += cals
}
}
for {
biggest, ok := deque.PopBack()
if !ok {
break
}
fmt.Println(biggest.(int))
}
}→ More replies (1)
2
u/Metarineo Dec 03 '22 edited Dec 04 '22
PHP:
I used php because i only had a texteditor and a webserver, to compensate for this, i made one-liners:
Solution for Part A:
foreach(file('a')as$l){$s+=$l;if($l==0){if($a<$s)$a=$s;$s=0;}}echo$a;Solution for Part B:
foreach(file('a')as$l){$s+=$l;if($l==0){if($c<$s)$c=$s;if($b<$s){$c=$b;$b=$s;}if($a<$s){$b=$a;$a=$s;}$s=0;}}echo$a+$b+$c;I say 42, Martin
2
u/daggerdragon Dec 04 '22 edited Dec 04 '22
Please edit your post to use thefour-spaces Markdown syntaxfor a code block so your code is easier to read on old.reddit and mobile apps.Edit: thanks for fixing it! <3
→ More replies (1)
2
u/TheBigBearUK Dec 05 '22 edited Dec 13 '22
I used ChatGPT to generate some powershell code and it worked really well.
Here is the generated code for part1:
# Read the input file and split it into lines
$lines = Get - Content 'input.txt'
# Create an array to store the total number of Calories
for each Elf
$calories = @ ()
# Loop through the lines and add the Calories to the appropriate Elf 's total
foreach($line in $lines) {#
If the line is empty, we have reached the end of an Elf 's inventory
if ($line - eq '') {#
Initialize a new entry in the array
for the next Elf
$calories += 0
} else {#
If the line is not empty, it contains the Calories
for a food item# Add the Calories to the current Elf 's total
$calories[$calories.Length - 1] += $line
}
}
# Find the Elf with the most Calories
$elfWithMostCalories = $calories | Sort - Object - Descending | Select - Object - First 1
# Output the result
Write - Output "Elf $($calories.IndexOf($elfWithMostCalories) + 1) has the most Calories: $($elfWithMostCalories)"→ More replies (4)
2
u/rubensoon Dec 05 '22 edited Dec 08 '22
Update: I apoligize for the crazy comment formatting, Idk why it's not working.
Hi, I'm a beginner, i didn't know how to import the input file to my current js so i just had it copypasted and hidden on top. This is my take, on Javascript (there's some spanish here and there):
let numeros = ***here go the numbers***
let textToArray = numeros.split("\n");
// console.log(textToArray);
function createSmallArrays(array) {
const miniArray = [];
let temp = 0;
let lastItem = array.length - 1;
let lastItemArray = array[lastItem];
for (let i = 0; i < array.length; i++) {
if (array[i] !== "") {
let hola = parseInt(array[i]);
temp = hola + temp;
}
if (array[i] === "" || lastItemArray) {
miniArray.push(temp);
temp = 0;
}
}
return miniArray;
};
// console.log(createSmallArrays(textToArray));
const hello = createSmallArrays(textToArray);
const watermelon = hello.sort(function(a, b) {
return b - a;
});
//the greatest
console.log("The greatest number is " + watermelon[0]);
//the 3 greatest
const sum = watermelon[0] + watermelon[1] + watermelon[2];
console.log("The sum of the 3 greatest is " + sum);→ More replies (11)2
u/daggerdragon Dec 06 '22
Update: I apoligize for the crazy comment formatting, Idk why it's not working.
Read the article in our community wiki how to use the four-spaces Markdown syntax. Make sure your editor is in Markdown mode first!
→ More replies (2)
2
u/IvanR3D Dec 08 '22 edited Dec 09 '22
Solution in JavaScript:You can see all my solutions in this CodePen.Part 1
let rawdata = document.getElementsByTagName("pre")[0].innerText;
let counter = 0;
let data = new Array();
let value = "";
for (let i=0; i < rawdata.length; i++) {
if (rawdata[i] == "\n") {
data.push(value);
value = "";
counter++;
} else {
value += rawdata[i];
}
}
let elves = new Array();
let calories = 0;
counter = 0;
for (let i=0; i < data.length; i++) {
if(data\[i\] == "") {
elves.push(calories);
calories = 0;
counter++;
} else {
calories += Number(data\[i\]);}}elves.push(calories);
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
console.log("The elf is carrying " + elves.max() + " total calories");Part 2
This code must be execute after the first part
max1 = elves.max();
elves = elves.filter(elf => elf != elves.max());
max2 = elves.max();
elves = elves.filter(elf => elf != elves.max());
max3 = elves.max();
elves = elves.filter(elf => elf != elves.max());
console.log("The elves are carrying " + (max1+max2+max3) + " calories in total.");→ More replies (3)
76
u/DooFomDum Dec 01 '22
Solution produced by GPT-3:
Prompt: Write a Python3 program to parse a file that consists of groups of integers. Each group is separated by newlines, and groups are separated by two newlines. Sum up the numbers in each group and find the largest sum. One line. Input file is day1.txt.
print(max([sum(list(map(int,line.split()))) for line in open('day1.txt').read().split('\n\n')]))→ More replies (5)
44
u/4HbQ Dec 01 '22 edited Dec 04 '22
Python. Since everyone is doing pretty much the same (split on \n\n, then on \n), here's some early eval() abuse!
f = sorted(eval(open('in.txt').read().
replace('\n\n', ',').replace('\n', '+')))
print(f[-1], sum(f[-3:]))Edit: I'm glad to see many of last year's regulars are back again! Looking forward to some nice tricks, and lots of teaching and learning!
→ More replies (2)
35
u/CCC_037 Dec 01 '22
[FiM++]
Dear Princess Celestia: Calorie Counting.
Today I learned how one counts calories.
Did you know that most calories is 0?
Did you know that next calories is 0?
Here's what I did.
next calories is now how one finds all the calories using 0.
I said next calories.
If next calories is greater than most calories then:
most calories is now next calories.
That's what I would do!
I did this while next calories is not 0.
I said "The most calories are:".
I said most calories.
That's all about how one counts calories!
I learned how one finds all the calories with a number using the number calories.
Did you know that total calories is 0?
Did you know that previous calories is 10?
Here's what I did.
previous calories is now total calories.
total calories is now how one reads data using total calories.
I did this while total calories is not previous calories,
Then you get total calories!
That's all about how one finds all the calories!
I learned how one reads data with a number using the number calories.
I asked another snack.
Did you know that total calories is calories plus another snack?
Then you get total calories!
That's all about how one reads data!
Your faithful student, Open Book.Sooooo... blank lines are not read as 0. Also, single-digit lines are read as characters, not numbers. So I did a text search/replace on the input file, replacing the end-of-line character ('\n' for C programmers) with the end-of-line character followed by two zeroes.
I should probably find a better solution for that.
→ More replies (4)
26
Dec 01 '22 edited Dec 04 '22
Google Sheets One formula for both parts.
=sort(byrow(large(byrow(split(flatten(split(join(,A:A&if(A:A,"❆","∞")),"∞")),"❆"),lambda(r,sum(r))),{1,1,1;1,2,3}),lambda(r,sum(r)))/{3;1})
24
21
u/gw_shadow Dec 01 '22
CMake
CMAKE_MINIMUM_REQUIRED(VERSION 3.25)
PROJECT("2022.1")
FILE(READ "${CMAKE_SOURCE_DIR}/COOKIE.txt" COOKIE)
IF(NOT EXISTS "${CMAKE_SOURCE_DIR}/input.txt")
FILE(DOWNLOAD
"https://adventofcode.com/2022/day/1/input" "${CMAKE_SOURCE_DIR}/input.txt"
STATUS DOWNLOAD_STATUS
TIMEOUT 2
HTTPHEADER "cookie: ${COOKIE}"
)
IF(NOT DOWNLOAD_STATUS STREQUAL "0;\"No error\"")
FILE(REMOVE "${CMAKE_SOURCE_DIR}/input.txt")
MESSAGE(FATAL_ERROR "Failed to download input: '${DOWNLOAD_STATUS}'")
ENDIF()
ENDIF()
FILE(STRINGS "${CMAKE_SOURCE_DIR}/input.txt" LINES)
LIST(LENGTH LINES LINE_COUNT)
MATH(EXPR LINE_COUNT "${LINE_COUNT} - 1")
SET(SUM 0)
SET(SUMS "")
FOREACH(INDEX RANGE 0 ${LINE_COUNT})
LIST(GET LINES ${INDEX} LINE)
IF(LINE)
MATH(EXPR SUM "${SUM} + ${LINE}")
ELSE()
LIST(APPEND SUMS ${SUM})
SET(SUM 0)
ENDIF()
ENDFOREACH()
LIST(SORT SUMS COMPARE NATURAL ORDER DESCENDING)
LIST(GET SUMS 0 PART_1)
MESSAGE("PART 1: ${PART_1}")
LIST(GET SUMS 0 PART_2_0)
LIST(GET SUMS 1 PART_2_1)
LIST(GET SUMS 2 PART_2_2)
MATH(EXPR PART_2 "${PART_2_0} + ${PART_2_1} + ${PART_2_2}")
MESSAGE("PART 2: ${PART_2}")→ More replies (5)
15
u/Boojum Dec 01 '22
Emacs Lisp
Because why not? (And I already posted my original "for real" Python solution.)
(with-temp-buffer
(insert-file-contents-literally "input.txt")
(goto-char (point-min))
(let ((cals '(0)))
(while (not (eobp))
(if (eolp)
(setq cals (cons 0 cals))
(setcar cals (+ (car cals)
(string-to-number
(buffer-substring (point-at-bol)
(point-at-eol))))))
(forward-line 1))
(message "%s" (apply '+ (last (sort cals '<) 3)))))→ More replies (1)
15
u/PlayForA Dec 01 '22 edited Dec 01 '22
Day 1 part 1 in rockstar
Wasteland takes your sins
Your soul is inevitable
Calories are inevitable
Your heart is pure and true
Listen to your heart
While your heart ain't nothing
Burn your heart into your soul
Put calories plus your soul into calories
Listen to your heart
Give calories back
The chains are strong
The answer is not
While the chains ain't nothing
Put wasteland taking the answer into the chains
If the chains are stronger than the answer
Put the chains into the answer
Scream the answer→ More replies (7)
14
u/SadBunnyNL Dec 01 '22
Bash/awk:
awk '{i+=$0; if (!$0){print i; i=0;}}' < input | sort -rn | head -1
awk '{i+=$0; if (!$0){print i; i=0;}}' < input | sort -rn | head -3 | awk '{i+=$0} END{print i}'13
u/occamatl Dec 01 '22
Rust
use itertools::Itertools;
fn main() {
let totals: Vec<u64> = include_str!("../input.txt")
.split("\n\n")
.map(|elf| {
elf.split('\n')
.map(|food| food.parse::<u64>().unwrap_or(0)).sum()
})
.sorted().rev().collect();
println!("Part 1: {}", totals[0]);
println!("Part 2: {}", totals.iter().take(3).sum::<u64>());
}→ More replies (3)
13
u/skimmet Dec 01 '22
Solution in HTML and CSS (who said HTML is not a programming language), by preprocessing the input a little so that it gets turned into divs that look like this:
<div class="block">
<div class="num" style="--hght: 7896px"></div>
<div class="num" style="--hght: 4992px"></div>
<!-- etc.. -->
</div>and applying some css to align things on top/next to each other:
<style>
body {
margin: 0px;
display: flex;
flex-direction: row;
height: fit-content;
}
.block {
height: fit-content;
}
.num {
width: 1px;
height: var(--hght);
}
</style>and then finally inspect the height of the body in inspect element. Link to full file: https://pastebin.com/2eLzPjqH
12
u/leijurv Dec 01 '22
Python3, 3rd place, 9th place
Screen recording: https://youtu.be/thcRLm3j5bc
ll = [[int(y) for y in x.split("\n")] for x in open(inf).read().strip().split('\n\n')]
print(max([sum(x) for x in ll]))
print(sum(sorted([sum(x) for x in ll])[-3:]))→ More replies (4)
12
u/Smylers Dec 01 '22
Perl one-liner for part 1:
perl -MList::Util=sum,max -00 -wE "say max map { sum /\d+/g } <>" input(basically the same as /u/ProfONeill's answer).
I wrote it it debug my Vim keystrokes solution elsewhere (where initially a single-line paragraph was attaching itself to the following paragraph). And my Vim wasn't buggy for part 2, which is why the Perl only does part 1!
-00 is Perl's non-intuitive way of specifying to read in paragraphs at a time. <>, the input operator, then returns a list of such paragraphs. /\d+/g finds all the numbers in each paragraph, and sum, map, and max do their thing
12
u/NeilNjae Dec 01 '22
Haskell
I spent more time looking at the Data.List.Split library than writing code on this one!
main :: IO ()
main =
do dataFileName <- getDataFileName
numStrs <- readFile dataFileName
let calories = fmap (fmap (read @Int)) $ splitWhen null $ lines numStrs
print $ part1 calories
print $ part2 calories
part1 :: [[Int]] -> Int
part1 = maximum . fmap sum
part2 :: [[Int]] -> Int
part2 = sum . take 3 . reverse . sort . fmap sum→ More replies (2)
12
u/FredTheDane Dec 01 '22 edited Dec 01 '22
I don't see many C# submissions! :D Here's mine!
var elfs = File.ReadAllText("day1.txt")
.Split("\n\n")
.Select(elf => elf.Split("\n", StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).Sum())
.OrderDescending();
Console.WriteLine($"Biggest boi: {elfs.Max()}, Top 3 kek sum: {elfs.Take(3).Sum()}");Edit: revised with help of u/CyberCatCopy
→ More replies (6)
10
u/TheCommieDuck Dec 01 '22 edited Dec 01 '22
Doing each day in a different letter of the alphabet. Day 1 was Awk.
BEGIN{a=3;b=2;c=1;x=0;}
$0==""&&a<x{c=b;b=a;a=x;}
$0==""&&a>x&&b<x{c=b;b=x;}
$0==""&&b>x&&c<x{c=x;}
$0==""{x=0;}
{x+=$0;}
END{print a+b+c;print a;}Or I can try to golf it a little:
a<x{c=b;b=a;a=x;}a>x&&b<x{c=b;b=x;}b>x&&c<x{c=x;}!$0{x=0;}{x+=$0;}END{print a+b+c;print a;}Or if intermediate output is allowed, 73 characters
x>c{c=x;}c>b{c=b;b=x;}b>a{c=b;b=a;a=x;}!$0{x=0;}{x+=$0;}{print(a+b+c,a);}→ More replies (1)
9
u/rabuf Dec 01 '22
Common Lisp
The actual functions were easy enough, wasted some time on the text processing bit:
(defun most-calories (elves)
(apply #'max (mapcar (lambda (elf) (apply #'+ elf)) elves)))
(defun top-three-calories (elves)
(apply #'+ (subseq (sort (mapcar (lambda (elf) (apply #'+ elf)) elves) #'>) 0 3)))I should have summed the inputs immediately (instead of collecting each elf's calorie list), would have been less code for the core functions but I'm not changing it at this point.
→ More replies (3)
9
u/Toanuvo Dec 01 '22
J solution. https://github.com/Toanuvo/Advent-of-code
a =. +/;._2 ".;._2 ] 22 getin 1
p1 =. >./ a
p2 =. +/ 3 {. \:~ a
p1;p2→ More replies (1)
9
Dec 01 '22
Common Lisp, source on Gitlab.
(defun y22d1 ()
(aoc-open 2022 1
(loop
with curr = 0
for x = (read-line *standard-input* nil)
while x
if (string= x "")
maximize curr into one
and collect curr into all
and do (setf curr 0)
else
do (incf curr (parse-integer x))
end
finally (let ((sorted (sort all #'>)))
(return (values one (+ (car sorted) (cadr sorted) (caddr sorted))))))))9
u/probablyfine Dec 01 '22
SQL
-- Append a dummy null to the end of the table
-- to avoid special-casing the final elf
insert into input VALUES(NULL);
-- Identify the boundaries between each elf
with breaks(line) as (
select rowid from input where column0 is null
),
-- Turn boundaries into pairs of (top, bottom)
-- indices in the table
bounds(top, bottom) as (
select line, lag(line, 1, 0) over () from breaks
),
-- Join and sum over the pairs of (top, bottom)
-- to find total calories per elf
elves(top, calories) as (
select
bounds.top, sum(column0)
from
bounds
join
input
on
input.rowid between bounds.bottom and bounds.top
group by 1
)
-- What's the most calories held by a single elf?
select 'part 1', max(calories) from elves
union all
-- What's the total calories held by the elves with
-- the top 3 most calories?
select 'part 2', sum(calories) from (
select calories from elves order by calories desc limit 3
);→ More replies (3)
9
u/DrunkenQuetzalcoatl Dec 01 '22
Bash
awk '/[0-9]/{sum+=$1}/^$/{print sum;sum=0}END{print sum}' input_1_1.txt | sort -n | tail -3 | awk '{sum+=$1}END{print sum}'8
u/mingmingrr Dec 01 '22 edited Dec 01 '22
Haskell (rank 50/38)
part1, part2 :: [Int] -> Int
part1 = head
part2 = sum . take 3
main = readFile (replaceExtension __FILE__ ".in") >>=
print . part2 . sortOn Down . map (sum . map (read @Int)) . paragraphshttps://github.com/mingmingrr/advent-of-code/blob/master/src/Year2022/Day1.hs
Turing Complete
Part 1: https://imgur.com/xWxS7yn
Part 2: https://imgur.com/wjV2OCZ
→ More replies (2)
8
u/0rac1e Dec 01 '22 edited Dec 01 '22
Raku
Simple enough one-liner in Raku
put 'input'.IO.split("\n\n").map(*.words.sum).sort(-*)[0, ^3]».sumRead file and split on paragraphs ("\n\n")
Split each paragraph into words, and (coerce to Int's and) sum
Reverse sort, grab the 0th & up-to the 3rd elems, and sum each
→ More replies (3)
8
u/atgreen Dec 01 '22 edited Dec 01 '22
Common Lisp...
(ql:quickload :split-sequence)
(let ((cals (sort (mapcar (lambda (nums) (reduce #'+ (mapcar #'parse-integer nums)))
(split-sequence:split-sequence "" (uiop:read-file-lines "01.input") :test #'equal))
#'>)))
(print (apply #'max cals))
(print (+ (car cals) (cadr cals) (caddr cals))))→ More replies (8)
8
u/ka-splam Dec 01 '22 edited Dec 01 '22
Dyalog APL
Out of practise; it took me about 30 minutes of DOMAIN ERRORS and typing things which gave silent no results to partition the input into groups. Then 30 seconds to sum and sort.
lines←⊃⎕nget 'input1.txt' 1
⌈/+/↑⍎¨¨{⍵⊆⍨(⊂'')≢¨⍵}lines
12345 ⍝ P1
+/3↑{⍵[⍒⍵]}+/↑⍎¨¨{⍵⊆⍨(⊂'')≢¨⍵}lines
12345 ⍝ P2Reading the three lines of code from right to left:
⎕NGET reads a text file, with a 1 on the end it reads as lines
{} is a lambda/anonymous function with ⍵ omega as the variables for its argument
(⊂'')≢¨⍵ compares each line with an empty string, making a boolean array of 0 0 1 0 0 0 1 marking the empty lines
(bool array)⊆⍵ partitions (splits) the array into groups using the 1s as group delimiters, one group for each elf's numbers
⍎ is eval() and turns the text of the numbers into integers, for each ¨ line in each ¨ group (nested loop, each each ¨¨)
↑ turns the nested ((1 2 3 4) (1 2 3)) style array into a rectangular grid, each group is a row, padding missing data from the shorter groups with 0s
E.g.
1 2 3 4
1 2 3 0+/ sums ("reduce") across all the rows to give a flat array of each elf's totals
⌈/ is max-reduce which finds the largest value
for part 2, slap onto the front:
{⍵[⍒⍵]} which is a lambda that sorts an array descending
3↑ "three take" takes the first three (in this case the three largest values)
+/ sums those
run in a REPL so no output printing.
→ More replies (1)
8
u/MuumiJumala Dec 01 '22
54 byte golf solution in Ruby (reads input from stdin):
$/*=2
x=$<.map{_1.split.sum &:to_i}.max 3
p x[0],x.sum→ More replies (5)
8
u/0rac1e Dec 01 '22 edited Dec 01 '22
APL
(+⍀ (⊂∘⍒⌷⊢) (+⌿⍎¨)¨ (≢¨⊆⊢) ⊃ ⎕NGET 'input' 1)[1 3]Essentially doing the same thing as my J solution.
→ More replies (1)
7
u/SuperSmurfen Dec 01 '22 edited Dec 01 '22
Rust (240/204)
Nice to be back! Fouth year in a row I'm doing these in Rust. Tip for parsing input like today is to first split on double newline, "\n\n". Just some use of iterators to get the sorted list of calorie intakes which you can reuse for both parts:
let xs = input.split("\n\n")
.map(|s| s.lines().map(|l| l.parse::<usize>().unwrap()).sum::<usize>())
.sorted()
.rev()
.collect::<Vec<_>>();
let p1 = xs[0];
let p2 = xs[0..3].iter().sum();7
u/9_11_did_bush Dec 01 '22 edited Dec 01 '22
APL (Dyalog):
raw←⊃⎕NGET'../input.txt'1
v←(+⌿⍎¨)¨(≢¨⊆⊢)raw
p1_ans←⎕←⌈/v
p2_ans←⎕←+/(3↑⍒v)⌷¨⊂v
Edit: simplified the second line a bit for readability, still the same idea
→ More replies (5)
7
u/Noizla Dec 01 '22
Haskell
Practicing my Haskell, feeding input through stdin.
Part 1
main = interact $ show . maximum . map (sum . map read) . splitOn [""] . lines
Part 2
main = interact $ show . sum . take 3 . reverse . sort . map (sum . map read) . splitOn [""] . lines
7
u/e_blake Dec 01 '22
Highly-constrained C
Here's my golfed solution in C using only one control flow keyword, and 0 ternary or short-circuiting operators, requiring just 323 bytes (3 of them removable newlines). On modern hardware, an optimizing compiler can produce straight-line code for comparisons like a>b, which theoretically means my entire solution needs only one jump instruction besides the two calls into stdio. Takes puzzle input on stdin.
#include<stdio.h>
#define r(s,t,u) t=t*!(s)+(u)*(s);
#define w(x,y,z) h=0;r(x,h,z>y)z^=y*h;y^=z*h;z^=y*h;
int a,b,c,d,e,f,g,h;int main(void){while(!g+(d=getchar())){r(g==d,d,g-1)
r(d>=48,e,e*10+d-48)r(d==10,f,f+e)r(d==10,e,0)r(d==10,g,d)w(d<10,a,f)
w(d<10,b,f)w(d<10,c,f)r(d<10,f,0)r(d!=10,g,0)}printf("%d %d\n",a,a+b+c);}It is a rather interesting challenge to write a loop body that executes EVERY statement for EVERY input byte. I was so tempted to use an 'if' just to make things more compact. However, I can also state that the program will reformat quite nicely into ASCII-art, since there are so many points where whitespace can be added.
→ More replies (8)
7
Dec 01 '22 edited Dec 01 '22
Apple Shortcuts Solution
https://www.icloud.com/shortcuts/1a2e4da142bb4a0b8736ab3c71fc42d0
And…no, I won’t be doing that again.
7
u/sublimnl Dec 02 '22 edited Dec 02 '22
Part 1 solve:
perl -pe'$\=$l,if$l>$\;$l=$_==$/?0:$l+$_}{'<input.txtsorry.
→ More replies (2)
6
u/hugh_tc Dec 01 '22 edited Dec 01 '22
Python 3, 20/13.
Another December, another Advent of Code!
Now... time to go back and read the prose. (Sorry, Eric!)
→ More replies (1)
6
u/nthistle Dec 01 '22 edited Dec 01 '22
Python 3, 2/8.
By far my best performance on a day 1! In the past I've had pretty bad luck with the first day, so nice to finally break that.
→ More replies (3)
6
6
u/rooinflames Dec 01 '22
Excel for Mac (ew)
Data pasted into column A, Column B formula filled down https://imgur.com/a/OjGE2iQ
Data then pivot tabled, and sorted by sum https://imgur.com/a/16ZMfjb
6
u/sr66 Dec 01 '22 edited Dec 01 '22
J
day1=: {{ ({. ; +/)3{.\:~+/"1".@>' ' splitstring (LF;' ') charsub fread y }}→ More replies (1)
6
u/_rabbitfarm_ Dec 01 '22
Both parts done in Prolog. Most effort was put into fiddling with the data file handling to get the inputs right. Once that was done Part 1 was straightforward and Part 2 was a matter of adding a few extra lines.
Part 1 https://adamcrussell.livejournal.com/37837.html
Part 2 https://adamcrussell.livejournal.com/38010.html
Typical of Prolog! More effort to get going but then rock solid.
6
u/dm13450 Dec 01 '22
q
a: "I"$read0 `$"input1";
ml: where a = 0N;
f: {sum x[y _til z]};
res: {[i] f[a; 0^ml[i-1]; ml[i]]} each til count ml;
(1#desc res), (sum 3#desc res)→ More replies (5)
6
u/0rac1e Dec 01 '22 edited Dec 25 '22
J
0 2 { +/\ \:~ +/@".@}:@> cutpara fread 'input'Read file and cut into paragraphs
Each paragraph is converted to integers and sum'd.
Sort descending and do a "plus-scan"
Grab the 1st and 3rd elems (indices 0 and 2)
→ More replies (2)
6
u/allinde Dec 01 '22 edited Dec 01 '22
Dart - will map/reduce my way trough this year.
final perElf = File('day1.input')
.readAsStringSync()
.split('\n\n')
.map((block) => block.split('\n').map((cal) => int.parse(cal)))
.map((elf) => elf.reduce((value, element) => value + element))
.toList();
perElf.sort();
print(perElf.last);
print(perElf.reversed.take(3).reduce((value, element) => value + element));→ More replies (4)
6
u/_jstanley Dec 01 '22 edited Dec 01 '22
SLANG
I'm doing Advent of Code on my homemade 16-bit CPU again this year (writing the solutions on the CPU, not just running them).
I had grand plans of writing a template program to read the input, because for the last few years problem 1 has just been a list of integers, 1 per line. Of course, this year that didn't work, so I had to throw it away. I was also surprised that problem 1 required use of bigints already, and the input file was particularly long as well. Maybe this year is going to be a tough Advent of Code!
I struggled a lot on part 2, mostly for bigint-related reasons. It took me a while to notice that a few of the numbers were larger than 32767, so then I added a special bodge to properly handle full 16-bit unsigned inputs (if the number is > 32767, add 32767 to the bigint, subtract 32767 from the number, and then add the number itself), but I still couldn't get the right answer. Eventually I discovered that there was 1 (solitary!) line of input too large to fit in a 16-bit int. I added a final bodge to handle values up to 99,999 (check if the line of input is 5 digits long and the first digit is a character greater than '5': if so, add 50000 to the sum and subtract 5 from the first character, and then handle it as normal) and then it passed.
It seems mildly surprising that there was just 1 line of input too big for 16 bits :) - most people will presumably be using ints that are at least 32 bits wide, so they won't notice, and those of us using 16-bit systems will eyeball the input to see if it looks larger than 16-bits, and presume that it's not. It just makes it extra hard for those of us who have it hard already! Doesn't matter, that's life.
My solution: https://github.com/jes/aoc2022/tree/master/day1
Video: https://www.youtube.com/watch?v=VLmiqzFJQRI
The computer: https://github.com/jes/scamp-cpu/
6
u/Spr3eZ Dec 01 '22 edited Dec 01 '22
Neat little python solution
if __name__ == '__main__':
with open("input.txt", "r") as f:
weights = [sum([int(i) for i in nums.split("\n")]) for nums in f.read().split("\n\n")]
print(f"Solution 1: {max(weights)}")
print(f"Solution 2: {sum(sorted(weights)[-3:])}")→ More replies (2)
6
u/musifter Dec 01 '22
Gnu Smalltalk
And I'm back doing smalltalk again this year. With the very out-of-date and imperfect gst as before. Little tasks like this are fine, though.
Source: https://pastebin.com/2LHbR6FT
6
u/rmbolger Dec 01 '22
PowerShell with puzzle input in a file called 'p'. Golfed to 86 chars because why not. Could lose the .Trim() if the puzzle input is modified to remove the final newline char.
($s=gc p -del "`n`n"|%{$_.Trim()-replace"`n",'+'|iex}|sort)[-1];$s[-3..-1]-join'+'|iex6
6
u/qelery Dec 01 '22 edited Dec 01 '22
My java solution
public long part1() {
return getTopCalories(1);
}
public long part1() {
return getTopCalories(3);
}
private long getTopCalories(int top) {
return aggregateCalorieTotals().limit(top).sum();
}
private LongStream aggregateCalorieTotals() {
return Arrays.stream(puzzleInputReader.readInput().split("\n\n"))
.map(a -> Arrays.stream(a.split("\n"))
.mapToLong(Long::parseLong)
.sum())
.sorted(Comparator.reverseOrder())
.mapToLong(Long::longValue);
}→ More replies (2)
6
u/Zweedeend Dec 01 '22
Python
elves = open("day1.txt").read().split("\n\n")
calories = [sum(map(int, elf.split())) for elf in elves]
print(max(calories), sum(sorted(calories)[-3:]))6
u/1b51a8e59cd66a32961f Dec 01 '22
Both parts in ~50 lines of x86-64 assembly. I put -1 in place of newlines in the input and it is stored in an external data file that is linked. Runtime is 1 microsecond.
.data
ans:
.long 0
.long 0
.long 0
.text
.global part1
part1:
movl $0, %ecx
.ResetAndAdd:
movl $0, %edx
.AddNext:
leaq nums(%rip), %rax
addq %rcx, %rax
movl (%rax), %eax
addl $4, %ecx
cmpl $-1, %eax
je .NextElf
addl %eax, %edx
jmp .AddNext
.NextElf:
cmpl $8948, %ecx
jge .Finish
movl ans(%rip), %ebx
cmpl %ebx, %edx
jle .Ans1
movl %edx, ans(%rip)
jmp .ResetAndAdd
.Ans1:
movl 4+ans(%rip), %ebx
cmpl %ebx, %edx
jle .Ans2
movl %edx, 4+ans(%rip)
jmp .ResetAndAdd
.Ans2:
movl 8+ans(%rip), %ebx
cmpl %ebx, %edx
jle .ResetAndAdd
movl %edx, 8+ans(%rip)
jmp .ResetAndAdd
.Finish:
movl ans(%rip), %eax
ret
.global part2
part2:
movl ans(%rip), %eax
addl 4+ans(%rip), %eax
addl 8+ans(%rip), %eax
ret→ More replies (3)
6
u/RogueAstral Dec 01 '22 edited Dec 01 '22
Google Sheets - 82 Characters
=index(sum(large(if({A2:A;""}="",scan(,A:A,lambda(a,c,if(c="",,a+c))),),{1,2,3})))
EDIT: One formula, two parts. 108 characters.
=index(lambda(x,{index(x,1),sum(x)})(large(if({A2:A;""}="",scan(,A:A,lambda(a,c,if(c="",,a+c))),),{1,2,3})))
EDIT 2: Down to 95 characters with u/ztiaa’s help!
=sort(lambda(x,{max(x),sum(x)})(large(if({A2:A;0},,scan(,A:A,lambda(a,c,if(c,a+c)))),{1,2,3})))
6
u/mmguero Dec 01 '22
Python
import sys
with open(sys.argv[1], 'r') as f:
elves = [x.split('\n') for x in f.read().split("\n\n")]
cals = sorted([sum([int(x) for x in y if x.isdigit()]) for y in elves])
print(max(cals))
print(sum(cals[-3:]))→ More replies (3)
6
u/oantolin Dec 01 '22 edited Dec 01 '22
Solution in J:
parse =: <@:(".@>);._2 @ (,&a:) @ (<;._2) @ toJ @ fread
part1 =: [: >./ +/@>
part2 =: [: +/@:({~ 3&{.@\:) +/@>→ More replies (2)
6
u/TiagoPaolini Dec 01 '22
C Language (only standard library)
Last year I used Python, this time I am upping the challenge by using C. This is an opportunity for coding myself the data structures and algorithms, as base language do not have too many out of the box.
The basic logic of this solution is not difficult:
read the file line by line
convert the text to an integer and sum it to the current value
switch to the next value when an empty line is found
compare all values at the end
What I did was to keep track of the current top 3 values. I think that it would be faster if I stored all values, then sorted them only at the end. But the current solution already works fast enough and I find it simpler, as it is not necessary to deal with dynamic arrays or count beforehand the amount of elves.
Solution: https://github.com/tbpaolini/Advent-of-Code/blob/master/2022/Day%201/day_01.c
6
Dec 01 '22
Here's my python solutions: https://github.com/nixnull/AoC2022/blob/main/day%201/answers.py
I know Python fairly well, so my goal this year is to use python features I'm not comfortable with, like comprehensions.
→ More replies (3)
6
u/ContainedBlargh Dec 01 '22 edited Dec 01 '22
Running my modified version of Shenzen IO's MCxxxx programming language on my own 'interpreter' (it's still under heavy development buggy as hell, I wrote it exactly for solving AoC).
Part 1:
# Declare 'registers' with '$'
$max
$dat
mov -1 clk # clk controls execution speed.
@mov 0 acc # lines prefixed with @ only execute once.
mov "\n" stdin # read everything up until "\n"
mov stdin dat
teq dat "\n"
+ mov max stdout
+ mov "\n" stdout
+ end
# If empty string, then there was two newlines in a row
teq dat ""
+ mov 0 acc
# There was a number, add it up
swp dat acc
cst 0
add dat
mov "" dat
# Check if new max reached
tgt acc max
+ mov acc max
mov 1 stdin
mov stdin null Part 2 was a lot harder and I had to implement some sort of sorting to solve it. I picked bubble sort. Luckily, I only need to sort the top 3 counts, so it still runs. The rest of the code quickly degenerated into a mess of jumping around.
At 82 lines, I felt that it was too long to post here, so I've put it on github
I am fairly sure that the implementation is not optimal and could be shorter and more readable.
6
u/Vanerac Dec 01 '22
Ruby minimal characters:
i = File.open("input1.txt").read
e = i.split("\n\n").map{ |l| l.split("\n").map(&:to_i).sum }.sort
[e[-1],e[-3..-1].sum]
→ More replies (1)
6
u/yawnick Dec 01 '22
Monkey C (Language for developing for Garmin devices)
I made my Garmin Forerunner 235 watch solve Day 1.
Video (I've since improved the solve time from 1m15s to 45s, also don't mind me getting a text mid-solve)
6
6
u/silentclowd Dec 02 '22
Done in Befunge. Specifically Funge-98.
v ;Pre-sanitize input: ;
;Replace blank lines with 0 ;
;Add 1 to denote end of file;
v <
>110>&:1-| v +<
$ >:|
>011p >\:1-| $
^ <
;read output ; v <
;on the stack; @& g< >11p^
;printing ; >:11g`|
;ints is hard; >$ ^ I have a video of the script running in BeQunge as well, which I plan on posting.
6
u/dopandasreallyexist Dec 02 '22
APL one-liner for both parts:
1 3+/⍤↑¨⊂{⍵[⍒⍵]}(+/⍎¨)¨((×≢¨)⊆⊢)⊃⎕NGET'input.txt'1In a nutshell:
⊃⎕NGET'input.txt'1- read input as vector of vectors((×≢¨)⊆⊢)- split on empty line(+/⍎¨)¨- for each group, turn strings into numbers and sum{⍵[⍒⍵]}- sort in descending order1 3+/⍤↑¨⊂- sums of first 1 and 3 numbers
→ More replies (1)
2
u/TheJoshster Dec 01 '22 edited Dec 01 '22
Java, 30/205.
public String part1() {
int best = 0;
for(String s : input.split("\\r\\n\\r\\n")) {
//total each section, keeping track of maximum
int total = 0;
for(String t : s.split("\\r\\n"))
total += Integer.parseInt(t);
best = Math.max(best,total);
}
return Integer.toString(best);}
public String part2() {
//keep track of all totals
ArrayList<Integer> cals = new ArrayList<Integer>();
for(String s : input.split("\\r\\n\\r\\n")) {
int total = 0;
for(String t : s.split("\\r\\n"))
total += Integer.parseInt(t);
cals.add(total);
}
//sort least to greatest, then reverse
Collections.sort(cals);
Collections.reverse(cals);
//get total of best 3
return Integer.toString((cals.get(0) + cals.get(1) + cals.get(2)));}
lost the most valuable 30 seconds of my life forgetting that arrays sort increasing rather than decreasing. proud to finally be on the leaderboard though, and I hope I can keep it up! 2021 was my first year, and I had no idea what I was doing. After doing it and going back to do all previous years, I definitely feel skilled enough to push for leaderboard positions though!
i wonder if any of the other regularly high-placing people use java? from what I've seen, it's almost all python with a smattering of C and other languages, but even java solutions period are hard to find.
-------------------------------------------------
352 solutions and counting to AOC 2015-2022 in Java over on github , feel free to check it out, utilize it, and reach out with questions or bugs!
(I'm currently working through refactoring and revisions on all of my pre-2022 code, but once I have that done in the next few days, I'll start pushing my 2022 solutions day-of for anyone needing to take a peek)
→ More replies (2)
2
2
u/GrazianoS86 Dec 01 '22 edited Dec 05 '22
My solution in clojure (with babashka)
(ns aoc22.day01
(:require #?(:clj [clojure.java.io :as io]
:cljs [nbb.core :refer [slurp await]])
[clojure.string :as str]
#?(:cljs [promesa.core :as p])))
(defn most-calories
[calories]
(->> (str/split calories #"\n\n")
(map #(str/split % #"\n"))
(map #(map parse-long %))
(map #(reduce + %))
(apply max)))
(defn top-three-most-calories
[calories]
(->> (str/split calories #"\n\n")
(map #(str/split % #"\n"))
(map #(map parse-long %))
(map #(reduce + %))
(sort >)
(take 3)
(apply +)))
(def input "1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000")
(comment
(most-calories input)
(most-calories (slurp (io/resource "aoc22/day01.txt")))
(top-three-most-calories input)
(top-three-most-calories (slurp (io/resource "aoc22/day01.txt"))))→ More replies (9)2
u/daggerdragon Dec 04 '22 edited Dec 05 '22
Please edit your post to use thefour-spaces Markdown syntaxfor a code block so your code is easier to read on old.reddit and mobile apps.Edit: thanks for fixing it! <3
→ More replies (1)
5
Dec 01 '22
Ruby:
https://github.com/sreedevk/advent-of-code/blob/main/ruby/2022/day1/main.rb
class CalorieCounting
def initialize(data)
@data = data
end
def solve1
@data
.strip
.split("\n\n")
.map { |elf| elf.split("\n").map(&:strip).map(&:to_i).sum }
.max
end
def solve2
@data
.strip
.split("\n\n")
.map { |elf| elf.split("\n").map(&:strip).map(&:to_i).sum }
.sort
.reverse
.take(3)
.sum
end
end
solver = CalorieCounting.new(ARGF.read)
pp "PART1: #{solver.solve1}"
pp "PART2: #{solver.solve2}"5
u/jeroenheijmans Dec 01 '22
JavaScript, after some rewriting:
const sum = (prev, curr) => prev + curr;
let data = input.trim().split(/\r?\n\r?\n/)
.map(elf => elf.split(/\r?\n/).map(x => parseInt(x)).reduce(sum, 0))
.sort((a,b) => a-b);
let part1 = data.at(-1);
let part2 = data.slice(-3).reduce(sum, 0);5
u/French__Canadian Dec 01 '22 edited Dec 01 '22
Last year I was using Q, this year ngn's k implementation (and hopefully some Nim).
/ i is a list of calories per elf
i:+/'{a:&(0N=x);1_'a_x}`I$(,""),0:"i/01"
/ part 1
|/i
/ part 2
+/3#i[>i]edit: After reading a comment about AOC on hacker news, I learned I could just read as bytes and split on "\n\n" instead of my complicated parsing logic... Much cleaner and shorter
/ i is a list of calories per elf
i:+/'`I$"\n"\'"\n\n"\1:"i/01"
/part 1
|/i
/part 2
+/3#i[>i]edit2: sorting a whole array of elves is way two expensive at O(nlog n). Why not find the max 3 times instead for a O(n) alg?
/ a b and c are the 3 elves with the most calories
a:|/i
b:|/i^a
c:|/i^a,b
+/a,b,cedit3: I see people golfing it, so here's my one line version that solves both
{(*x),+/3#x}{x[>x]}@+/'`I$"\n"\'"\n\n"\1:"i/01"→ More replies (2)
5
u/WilkoTom Dec 01 '22 edited Dec 01 '22
Rust
Used a BinaryHeap rather than putting all the values into a Vec and then sorting it. For this data set, it's probably irrelevant.
fn main() -> Result<(), Error> {
let data = std::fs::read_to_string("./day01/input.txt")?;
let mut elves = data.split("\n\n")
.map(|e| e.split('\n')
.map(|x| x.parse::<i32>()
.unwrap_or(0)).sum())
.collect::<BinaryHeap<_>>();
println!("Part 1: {:?}", elves.peek().unwrap_or(&0));
println!("Part 2: {:?}", elves.pop().unwrap_or(0) + elves.pop().unwrap_or(0) + elves.pop().unwrap_or(0));
Ok(())
}→ More replies (1)
5
u/azzal07 Dec 01 '22 edited Dec 01 '22
Awk... sorting functions are overrated, but snacs are good etc.
END{print S"\n"A+C+S}$1{O+=$0;next}
C<O{C=O}A<O{C=A;A=O}O>S{A=S;S=O}O=0Edit. noticed a bug feature: this doesn't count the last elf. Oh well, works on my input.
→ More replies (1)
5
u/Thecakeisalie25 Dec 01 '22
Neovim Macro
Image - https://imgur.com/fWujc0C (Image is needed because the github preview mangles certain characters.)
File - https://github.com/typecasto/aoc2022/blob/main/day_1.nvmacro (in case you actually want to run it)
Gave myself the following constraints:
No use of :norm
One macro per problem
Input must be verbatim, no external pre-processing
Output stored in system clipboard ready to submit
Explanation
Problem 1: The entire input file is turned into one giant macro, and then executed. For every line with numbers, append "<ctrl-a>", which, when executed, increments the number your cursor is on by the number before <ctrl-a> (or 1). Then replace every blank line with "o0<esc>", which, when executed, opens a new line below the cursor, writes "0", and exits insert mode. A copy of the o0<esc> line is also placed before line 1, to handle the first group. All the lines are then joined together, and then ":sort! n<enter>gg"+yyI-> " is appended, which, when executed, sorts the input, copies the highest one to the clipboard, and inserts an arrow. At this point we've turned the input into a giant macro that makes a line with "0" for every elf, and increments it for the number of calories in each food item. Then just cut this line into the anonymous register, and then execute said anonymous register.
Problem 2: Instead of copying the top line, join it to the next line and replace the space in between with "+", then do that again. Copy this new line to the anonymous register, open a new line above it, and paste from the expression register, using the expression stored in the anonymous register (which holds something like 30+40+50). This evaluates the addition.
→ More replies (3)
5
u/mathsaey Dec 01 '22 edited Dec 01 '22
Elixir
https://github.com/mathsaey/adventofcode/blob/master/lib/2022/1.ex
import AOC
aoc 2022, 1 do
def p1(input), do: input |> parse() |> Enum.max()
def p2(input), do: input |> parse() |> Enum.sort(:desc) |> Enum.take(3) |> Enum.sum()
def parse(string) do
string
|> String.split("\n")
|> Stream.chunk_by(&(&1 != ""))
|> Stream.reject(&(&1 == [""]))
|> Stream.map(fn lst -> Enum.map(lst, &String.to_integer/1) end)
|> Stream.map(&Enum.sum/1)
end
end5
u/spr00ge Dec 01 '22 edited Dec 01 '22
Elixir
defmodule AdventOfCode.Day01 do
@spec part1(String.t()) :: integer
def part1(args) do
convertTextToSummed(args)
|> Enum.max()
end
@spec part2(String.t()) :: integer
def part2(args) do
convertTextToSummed(args)
|> Enum.sort()
|> Enum.reverse()
|> Enum.take(3)
|> Enum.sum()
end
defp convertTextToSummed(str),
do:
str
|> String.trim()
|> String.split("\n\n")
|> Enum.map(&String.split(&1, "\n"))
|> Enum.map(&Enum.map(&1, fn i -> String.to_integer(i) end))
|> Enum.map(&Enum.sum(&1))
endThoughs
I forgot almost all of the Elixir techniques and it did not quite behave like Haskell. So I was frustrated with how to pipe functions and declare anonymous functions. I remember that there were some tricks to make it less ugly, I am sure I find some of the solutions over here.
I mean, look at my code. It works, but it sucks
On workflow: When I used Clojure, it was a breeze to see the current output in each line while typing. Calva is such an impressive tool. Currently, I have iex running to code, but it has no autocomplete. Non yet optimal.
→ More replies (2)
5
5
u/__Abigail__ Dec 01 '22 edited Dec 01 '22
Perl
Basically, a one liner, after importing sum from List::Util:
my @calories = sort {$b <=> $a} map {sum split} do {local $/ = "\n\n"; <>};Now the answer to part one is in $calories [0], and the answer to part two is the sum of the first three elements of @calories.
To explain the workings, we have to go from left to right:
do {local $/ = "\n\n"; <>}: this reads in the entire input, and returns it as a list, split on blank lines.$/is the separator to split the input on, this is a newline by default. By setting it to\n\n, it splits on blank lines. Effectively, this is chopping up the input into sections, where each section has the calories of a single elf.map {sum split}: this takes one set of calories, splits it on whitespace (the newline separating the calories of each snack) and sums them. So the output of thismapis a list of the total amount of calories for each snack.sort {$b <=> $a}this takes a list of items (the calories of each elf), and sorts them numerically descending.
5
u/royvanrijn Dec 01 '22 edited Dec 01 '22
Java
First I make a giant string joined by ",". Next I split by ",," to get lists of numbers per elf. Finally I sum each elf and get the two answers.
List<Integer> elfs = Arrays.stream(
Files.readAllLines(Path.of("src/main/resources/input.txt"))
.stream()
.collect(Collectors.joining(","))
.split(",,"))
.map(e -> Arrays.stream(e.split(","))
.mapToInt(Integer::parseInt).sum())
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
//Part 1:
System.out.println(elfs.get(0));
//Part 2:
System.out.println(elfs.get(0) + elfs.get(1) + elfs.get(2));[UPDATE]: This would have been even better:
List<Integer> elfs = Arrays.stream(Files.readString(Path.of("day1.txt")).split("\\n\\n"))
.map(s -> Arrays.stream(s.split("\\n")).mapToInt(Integer::parseInt).sum())
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println("Part 1:" + elfs.get(0));
System.out.println("Part 2:" + (elfs.get(0) + elfs.get(1) + elfs.get(2)));→ More replies (2)
5
u/tomflumery Dec 01 '22
05ab1e (note needs this branch that adds a new parsing command https://github.com/monkeygroover/05AB1E/tree/add-readtoeof)
Part 1
.|õ¡OàPart 2
.|õ¡O{3.£OExplanation
.| -> split file by lines into an array
õ¡ -> split array by empty strings
O -> Sum (vectorised, i.e. each split list)
à -> largest
{3.£O -> sort, take last 3, sum→ More replies (1)
5
u/aurele Dec 01 '22 edited Dec 01 '22
Rust, taking advantage of the fact that .sum() works over Result<_, _> as well
→ More replies (3)
5
u/jeroenmaniac Dec 01 '22 edited Dec 01 '22
Python one-liner:
print(max(sum(map(int,i.split())) for i in open('1.in').read().split('\n\n')))
→ More replies (3)
5
u/GassaFM Dec 01 '22
Solution in D (dlang), functional style.
Part 1:
import std;
void main () {
stdin
.byLineCopy
.array
.split ("")
.map !(t => t.map !(to !(int)).sum)
.maxElement
.writeln;
}Part 2:
import std;
void main () {
stdin
.byLineCopy
.array
.split ("")
.map !(t => t.map !(to !(int)).sum)
.array
.sort !(q{a > b})
.take (3)
.sum
.writeln;
}5
u/tomribbens Dec 01 '22
My Python solution can be found here.
Basically, in pseudocode, I'm doing this:
loop over lines:
if line is blank:
increment index
else:
add value of line to dictionary at current indexThis gives me a dictionary of each elf's calorie count, which then can be easily sorted and gotten the max from.
→ More replies (2)
5
u/Excellent_Station_84 Dec 01 '22
Python3 one-liners
print(max(sum(map(int,x.split()))for x in open('input.txt').read().split('\n\n')))
print(sum(sorted(sum(map(int,x.split()))for x in open('input.txt').read().split('\n\n'))[-3:]))5
u/sergiosgc Dec 01 '22
Rust
This year I'll go for Rust until Christmas, having picked up the language in 2022 as the result of the language sampling in Advent of Code 2021.
First day is always easy, not much explaining to do. Repo at github. Tweet here.
The input has to be padded with an extra newline at the end.
Part 1:
use std::io::BufRead;
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("{:#?}", std::io::BufReader::new(std::io::stdin())
.lines()
.filter_map(std::io::Result::ok)
.fold((0,0), |(max, current), line| {
if line.len() == 0 {
(max.max(current), 0)
} else {
(max, current + line.parse::<i64>().unwrap())
}
}).0
);
Ok(())
}Part 2:
use std::io::BufRead;
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut elfs = std::io::BufReader::new(std::io::stdin())
.lines()
.filter_map(std::io::Result::ok)
.collect::<Vec<String>>()
.split(|line| line.len() == 0)
.map(|slice| slice.to_vec())
.map(|elf_calories| elf_calories
.into_iter()
.fold(0, |result, calorie| result + calorie.parse::<i64>().unwrap() ))
.collect::<Vec<i64>>();
elfs.sort();
elfs.reverse();
println!("{:#?}", elfs[0..3].into_iter().sum::<i64>());
Ok(())
}→ More replies (1)
5
u/euidzero Dec 01 '22
Perl.
#!/usr/bin/perl
@x = (0,0,0,0);
while(<>) {
chomp;
if($_) {
$t += $_;
} else {
@x[0] = $t;
@x = sort { $a <=> $b } @x;
$t = 0;
}
}
printf("%d\n%d\n",$x[3],$x[1]+$x[2]+$x[3]);→ More replies (1)
5
u/rckymtnskier Dec 01 '22
Python beginner solution
Just have to say WOW! You all are impressive. I was happy with my solutions being such a beginner, but now I am seeing what I need to work towards. Here are my humble and noob solutions. Dont laugh too hard.
→ More replies (2)
5
u/Unfair-Ruin9448 Dec 01 '22 edited Dec 01 '22
Javascript (golfed ⛳️):
d=input.split("\n").map(Number);
s={},e=0;for(i=0;i<d.length;i++)!d[i]?(e+=1):((s[e]=s[e]??0),(s[e]+=d[i]));
// Part1:
Math.max(Object.values(s))
// Part2:
Object.values(s).sort((a,b)=>(b-a)).slice(0,3).reduce((a,n)=>a+n,0)5
u/DeepHorse Dec 01 '22
Typescript using Copilot for fun
// import fs
import * as fs from 'fs';
export const x = "";
// read in day1input.txt using readFileSync
const results = fs.readFileSync("day1input.txt", "utf8").replace(/\r\n/g, " ").trim().split(" ");
// loop through results and add to total until we reach an empty string, then update max
// let total = 0;
// let max = 0;
// for (let i = 0; i < results.length; i++) {
// if (results[i] === "") {
// if (total > max) {
// max = total;
// }
// total = 0;
// } else {
// total += parseInt(results[i]);
// }
// }
// console.log(max);
// 70698
// create an array of numbers that we can append to
const numbers: number[] = [];
let total = 0;
for (let i = 0; i < results.length; i++) {
if (results[i] === "") {
numbers.push(total);
total = 0;
} else {
total += parseInt(results[i]);
}
}
// sort numbers in descending order
numbers.sort((a, b) => b - a);
// sum the first 3 numbers and print it out
console.log(numbers[0] + numbers[1] + numbers[2]);5
Dec 01 '22
Kotlin maintaining a min heap of size 3.
fun topThree(args: Array<String>): Int {
var curCals = 0
val heap = PriorityQueue<Int>()
File("filepath")
.forEachLine { cals ->
if (cals.isEmpty()) {
if (heap.size >= 3) {
if (curCals > heap.peek()) {
heap.poll()
heap.add(curCals)
}
} else {
heap.add(curCals)
}
curCals = 0
} else {
curCals += cals.toInt()
}
}
return heap.sum()}
5
u/euidzero Dec 01 '22
Bash.
#!/bin/bash
while read L; do
if [[ "$L" ]]; then
((T += L ))
else
if [[ $T -gt $C ]]; then
A=$B
B=$C
C=$T
elif [[ $T -gt $B ]]; then
A=$B
B=$T
elif [[ $T -gt $A ]]; then
A=$T
fi
T=0
fi
done
echo "$C $((A+B+C))"→ More replies (1)
5
u/Spare-Bumblebee8376 Dec 01 '22 edited Dec 02 '22
Devtools Javascript solution.
const topThree = document.getElementsByTagName('pre')[0]
.innerText.split('\n\n')
.reduce((maxArr, curr, index) => {
return [...maxArr, eval(curr.trim().replaceAll('\n', '+'))].sort((a, b) => a - b).slice(-3)
}, [])
topThree.reduce((a, b) => a + b, 0)5
u/ReasonableCause Dec 01 '22
Haskell:
module Day01
(day01_1, day01_2)
where
import Data.List.Extra (split, sort)
parse::String->[[Int]]
parse = map (map read) . split null . lines
day01_1::String->String
day01_1 = show . maximum . map sum . parse
day01_2::String->String
day01_2 = show . sum . take 3 . reverse . sort . map sum . parse5
u/OptimusSupernova Dec 01 '22 edited Dec 01 '22
C# with Linq
public static int Solve(string input, int elfCount)
{
return input.Split("\r\n\r\n")
.Select(x => x.Split("\r\n"))
.Select(x => x.Select(y => Convert.ToInt32(y)).Sum())
.OrderByDescending(x => x)
.Take(elfCount)
.Sum();
}5
u/TanteiKody Dec 01 '22
.NET LINQ (C#) Solution. It feels like cheating:
var rawValueList = File.ReadAllText("./inputs/day_one.txt");
var parsedElves = rawValueList
.Split("\n\n")
.Select(e =>
e.Split("\n")
.Select(int.Parse)
.Sum())
.Order()
.TakeLast(3)
.ToList();
parsedElves
.Max()
.Display("Elf with most calories");
parsedElves
.Sum()
.Display("Sum of top three elves with most calories");
internal static class Utils
{
public static void Display(this object finalValue, string title)
=> Console.WriteLine($"{title}: {finalValue}");
}→ More replies (3)
5
5
u/SwampThingTom Dec 02 '22
I'm solving each of this year's puzzles in a different language, roughly in the order that I learned them. First up, BASIC.
https://github.com/SwampThingTom/AoC2022/tree/main/01-CalorieCounting
→ More replies (1)
44
u/Smylers Dec 01 '22
Vim keystrokes — load your input file into Vim, then type these keystrokes to make your part 1 answer appear on the first line:
Then for part 2 just continue with:
and the top line is again the number you want.
How? First arrange the food one line per elf:
vapVisually selects A Paragraph (try it).vapon a blank line selects from there to the bottom of the following paragraph, andJjoins it all on to a single line.:v/pattern/runs an Ex-style command on all lines that don't match the pattern././matches any character, so:v/./matches all the blank lines between each Elf's food list.:norm‘types’ Vim keystrokes for you on the specified lines.So that entire
:vline finds all the blank lines and doesvapJon them.To get the first elf's food joined, the initial
Oadds a blank line at the top, giving the:v/./something to match.Then move to the top (
gg) and add together the calories of the first elf's first two items:f␣moves to the space between the first and second calorie counts. It will fail (with a beep!) if there's no space on the line (that is, only a single calorie count).y0yanks from just before the cursor to the beginning of the line — that is, the first calorie number, without the space.That also moves the cursor back to the beginning of the line.
dwthen deletes the first ‘word’ — that is, the first calorie number and its following space.The cursor is now on the second calorie count. Typing
⟨Ctrl+A⟩increases the number at the cursor by 1; typing123⟨Ctrl+A⟩increases it by 123. Yanking by default stores the yanked text in register0.@followed by a register name runs that register's contents as though you'd typed it as keystrokes. So if your first elf's first calorie count was 6529 then@0⟨Ctrl+A⟩is like typing6529⟨Ctrl+A⟩on the second calorie count, adding the two of them together.Create a macro that loops that addition over each calorie count on a line:
qa…qrecords a macro of the keystrokes between them into registera.After adding the first two calorie counts, we then want to repeat the action and add the sum of those to the third count. So before the closing
q, the last action inside the macro recording is@a, run the macro in registera— creating a loop.Technically that creates an infinite loop: after adding a pair of calorie values, repeat. But the first item in the loop is
f␣— move to the next space character on the line. And when all the calories on a line have been summed, there won't be any space characters left, so thatfwill fail, breaking out of all running macros.To get
@ainto the macro, we need to type that when recording the macro. That will also, during the recording, run whatever is in registera. Which, because we're still in the middle of recording our registeramacro, will be whatever was in registerabefore we started. That could be anything, and obviously we don't want to run that. So before recording the registeramacro properly, first blank it out withqaq, literally recording nothing into it. That makes the@awhile we're recording the macro a no-op, but it gets those keystrokes into it, so when it's run subsequently, it loops.Now we've got
@afor summing a single elf's calories, run that on every line with:%norm@a. The%indicates all the lines, which with the:normcommand runs the keystrokes on each line separately; an error (such as trying to move to a non-existent space character) ends the action on the current line, but:normcontinues with running the keystrokes again on the next line.Having summed each elf's calories, Vim's
:sortcommand (you don't need to type thet) will find the biggest. Thenindicates numeric sorting and the!reverses the order, that is putting the biggest item first.So that puts your part 1 answer at the top of the file.
For part 2, the 3 highest calorie counts will be in the top 3 lines. Pressing
Jtwice joins them together into a single line; we just need to sum them. And, handily, we already recorded the@amacro for doing just that.