#AoC 2022 | Day 1 | Solutions & Spoilers
1604 messages ยท Page 2 of 2 (latest)
Literally just does the task and isnt hard coded.
why the function
its a bit more reusable
where do you reuse it in the file
I feel like, you guys are the type of people to set up a base class and use polymorphism for this type of thing
Fine fine u win
I was actually close to doing that
๐
why
If u did that, I would have literally quit coding.
I end up copying and pasting my read file function quite a lot between days
use a module
was considering just doing a base class or mixin to bring it in
having an aoc library with a fileread function should be pretty helpful for the next days
pretty much the only thing youll do over and over again
I like doing it each time since it lets you customise how you parse your input each time
Yeah, that's the reason I decided not to
some days will all be the same, but having a solution-specific one can clean up the rest of your code
that plus I like being able to copy paste the whole solution somewhere
unless you're like me who doesn't bother copying and pasting to/downloading a file just to read it again
i just copy and paste and formulate solutions in the REPL
if you wanted to go balls to the wall you could probably write a generic one then override it if you want to do more on other days
The way I do it is I have a file dedicated to running the AoC solutions (there's some QoL features like progress bars and input fetching in there), and by default it'll pass in a list of all the lines from the files, but can also be made to pass in the raw input. Has worked pretty well for me
one line? damn... my one is terrible
with open("input.txt", "r", encoding="UTF-8") as f:
counter = 0
for line in f:
line = line.replace("\n", "")
if line == "":
data.append(counter)
counter = 0
else:
counter += int(line)
data.sort()
top_three_total = 0
for i in (range(-1, -4, -1)):
top_three_total += data[i]
I may have overengineered my solution...
from typing import List, Dict
import re
def read_file_as_string(filename: str) -> str:
with open(filename, 'r') as input_file:
return input_file.read()
def split_on_empty_lines(input_str: str) -> List[str]:
regex = "\n[ \t\n]+"
return re.split(regex, input_str)
def split_by_elf_and_format(input_list: List[str]) -> Dict[int, List[int]]:
output = {}
for curr_elf, substr in enumerate(input_list):
output[curr_elf] = [int(x) for x in substr.split("\n") if x]
return output
def sum_elves(elf_dict: Dict[int, List[int]]) -> Dict[int, int]:
output = {}
for elf, calories in elf_dict.items():
output[elf] = sum(calories)
return output
def main(filename: str) -> None:
file_input = read_file_as_string(filename)
elves = split_on_empty_lines(file_input)
elves = split_by_elf_and_format(elves)
totals = sum_elves(elves)
sorted_totals = sorted(totals.values(), reverse=True)
print(f"The maximum number of Calories carried by an elf is {sorted_totals[0]}")
print(f"The total number of Calories carried by the top 3 elves is {sum(sorted_totals[0:3])}")
if __name__ == "__main__":
from sys import argv
if "--test" in [v.lower() for v in argv]:
input_file = "inputs/day_1/test.txt"
else:
input_file = "inputs/day_1/input.txt"
main(input_file)
431/219
with open('input.txt') as f:
data = f.read().split('\n\n')
matches = []
for line in data:
matches.append(sum(map(int, line.split())))
print(max(matches)) #Part 1
print(sum(sorted(matches)[-3:])) #Part 2
Normally for [ \t\n], I'd use the shortcut \s instead, which does any whitespace in [ \t\n\r\f\v], but the last 3 are rare enough that they're pretty close to equivalent.
TIL that \s, \f, and \v exist. I knew about \r, but I've never come across it in practice
windows & HTTP newlines use \r\n, you'll rarely see it elsewhere
i miss 2021 where i onelined like 4 days with numpy
then you should try APL ๐
or alternatively k
but my pretty glyphs ๐ญ
no pretty glyphs for you โ
\f\v were both new to me when I googled the exact definition of \s to post my reply. Form Feed and Vertical Tab apparently. Not sure if those still have modern applications.
Its nice to use in terminal applications when you want to clear a line
That's true as well
Apparently \f is used for page breaks
anything to avoid ansi escapes 
okay
i need some help
i got the first one right
but the secound one is giving me a lot of problems
what issues are you having?
i've tried a bunch of diffrent ways to get the top three but i always get the same number 203454
What is this channel for? Is it a special event or something?
I sorted the elves from highest to lowest. Here are the index values of the elves you have summed (assuming your parsing is correct):
0, 5, 183, 227
๐ป
Actually, turns out there are a lot of possible combinations to get that result
would you like to post your code?
&aoc about
Advent of Code (AoC) is a series of small programming puzzles for a variety of skill levels, run every year during the month of December.
They are self-contained and are just as appropriate for an expert who wants to stay sharp as they are for a beginner who is just learning to code. Each puzzle calls upon different skills and has two parts that build on a theme.
Sign up with one of these services:
GitHub
Google
Twitter
Reddit
For the global leaderboard, the first person to get a star first gets 100 points, the second person gets 99 points, and so on down to 1 point at 100th place.
For private leaderboards, the first person to get a star gets N points, where N is the number of people on the leaderboard. The second person to get the star gets N-1 points and so on and so forth.
Come join the Python Discord private leaderboard and compete against other people in the community! Get the join code using .aoc join and visit the private leaderboard page to join our leaderboard.
my code is this
file1 = open('aocday1input.txt', 'r')
Lines = file1.readlines()
i=0
maxcal=0
maxcal2=0
maxcal3=0
elfs=[]
for line in Lines:
if line.strip():
i+=int(line.strip())
else:
if i > maxcal:
maxcal3=maxcal2
maxcal2=maxcal
maxcal=i
elfs.append(i)
i=0
else:
i=0
elfs.sort()
print(sum(elfs[-3:]))
It's a bit... verbose
?
This is mine. ```py
def main(data: str):
elves = [sect.splitlines() for sect in data.split("\n\n")]
calories = [sum(map(int, elf)) for elf in elves]
# part 1
print(max(calories))
# part 2
print(sum(sorted(calories)[-3:]))
open(file).read()
I run everything from this file. ```py
import argparse
import sys
import importlib
def getdata(day: int, *, example=False):
suffix = ""
if example:
suffix = ".example"
file = f"data/day{day}{suffix}.txt"
try:
with open(file) as f:
return f.read()
except FileNotFoundError:
print(f"ERR: Could not load data file {file}.", file=sys.stderr)
sys.exit(1)
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("day", type=int)
parser.add_argument("--example", action='store_true')
return parser.parse_args()
def main(args):
data = getdata(args.day, example=args.example)
importlib.import_module(f"day{args.day}").main(data)
if name == "main":
sys.exit(main(get_args()))
then I can run python aoc.py 1
You may be overthinking it.
don't worry about the max first. Just calculate how many calories each elf is carrying
# part 1
print(max(sum(map(int,i.split())) for i in open(r"aoc 2022\day 1\input.txt").read().split("\n\n")))
# part 2
print(sum(sorted(sum(map(int,i.split())) for i in open(r"aoc 2022\day 1\input.txt").read().split("\n\n"))[-3:]))
one-liners baby
i just figured out the problem
this code works
file1 = open('aocday1input.txt', 'r')
Lines = file1.readlines()
i=0
elfs=[]
for line in Lines:
if line.strip():
i+=int(line.strip())
else:
elfs.append(i)
i=0
how does if line.strip() work
it remove whitespace surrounding a string
line.strip removes the newline char. if a line is just a newline then it is basically blank
basically checks if it isn't blank
oh
print(max([sum([int(calorie) for calorie in elf.split('\n')]) for elf in open("input.txt").read().split("\n\n")]))
i did this
eh mine's shorter
ah
i was challenged to do it by parsing the input into a 1d array of integers, transforming newlines into 0s
came up with this: ```py
parse input
i = sum([[*map(int,i.split()),0] for i in open(r"aoc 2022\day 1\input.txt").read().split("\n\n")], [])
s = 0
print(max((s,s:=0)[0]for j in i if(s:=s+j,j==0)[1]))
@violet hound Alright I have just turned into u XD
from pathlib import Path
class FileData:
def __init__(self, path):
self._path = Path(path)
self.input = self.file_opener()
def file_opener(self) -> str:
with open (self.path, 'r') as f:
return f.read()
@property
def path(self) -> Path:
return self._path
class ElfData(FileData):
def __init__(self, *args):
super().__init__(*args)
def _elf_sums(self) -> list:
splitter = self.input.splitlines()
elf_list = []
temp_var = 0
for i in splitter:
if not i:
elf_list.append(temp_var)
temp_var = 0
continue
temp_var += int(i)
return elf_list
@property
def highest_value(self):
elf_list = self._elf_sums()
return max(elf_list)
elves = ElfData('input.txt')
print(elves.highest_value)
Nice :)
Mine
e = sorted(
[sum(list(map(int, i))) for i in [i.split("\n") for i in inp.split("\n\n")]],
reverse=True,
)
print(e[0])
print(sum(e[:3]))
super is not needed though
Bit clunky
I made a base class for the prompt ๐ญ
now write some unit tests :)
Are u proud of me?
Why? I need to make the path stuff.
Whats that?
__init__ is inherited anyway
Lmao i forgot what sorted and map are lol.
You aren't changing it, so you can get rid of the __init__ in the subclass
I see alright.
I was using max for the first one but switched to sorted so I could do both in 1
I hate this font, btw
Lol ye idk.
I just used splitlines and split it until i got the blank line. and then u checked if there was a blank line 
then appended to a list
Testing is a way of proving your code works, and protecting against regression. With a unit test, you can give an input to a "unit" of code (e.g. a function or class), and then when an output is generated you assert that the output is what you expect
Was gonna use splitlines but didn't wanna have to rejoin them again
I love list comps
^ this was my unit tests for today
They look so nice
I see. Wait whats regression lol
So if you were to change or enhance your code, you can run the tests to check that you didn't break anything
Yikes thats simplistic, but very compact lmao.
I see.
For me the challenge is making it work on one line without any kind of signpost variables or stuff like that
I have pytest installed and I can run pytest over the functions I wrote to run the tests and tell me if they all passed or if any failed
I like them like that
I see.
My code kept failing because the input had a newline EOF
Tho idek why someone used a generator for this.
Monkeypatched the input ๐
I saw someone code a generator just for part 1 ๐
๐ญ
I forgot what does [:3] do?
First 3 elements
Oh fr? So is it a list?
But they couldve not used reverse, and done [-3:] instead
Whats a map. I used it awhile ago, but don't remember it.
Map applies a function to every item in an iterable
map(int, i) is going to return a copy of i where every item inside of the list has now been converted to an int
Equivalent to i = [int(item) for item in i]
Ah
from pathlib import Path
class FileData:
def __init__(self, path):
self._path = Path(path)
self.input = self.file_opener()
def file_opener(self) -> str:
with open (self.path, 'r') as f:
return f.read()
@property
def path(self) -> Path:
return self._path
class ElfData(FileData):
def _elf_sums(self) -> list:
splitter = self.input.splitlines()
elf_list = []
temp_var = 0
for i in splitter:
if not i:
elf_list.append(temp_var)
temp_var = 0
continue
temp_var += int(i)
return sorted(elf_list, reverse=True)
@property
def total_list(self) -> list:
return self._elf_sums()
@property
def highest_value(self) -> int:
return max(self.total_list)
@property
def three_elf_sum(self) -> int:
return sum(self.total_list[:3])
elves = ElfData('input.txt')
print(elves.three_elf_sum)
```Lmk what u think
still don't need the reversed
Ahh yeah you're right saves me some more ๐
@simple jetty how would u rate the code?
True one liner now
Looks good
POV: me being to lazy to turn it into a one-liner
Just gonna say I didn't use one-liner for the sake of code-readability ๐
ty ๐
holy
neat
Ah, I see lots of people used split("\n\n"). That would be a lot easier than what I did with checking if the line was empty to move on.
I didnt even check if the line was empty.
I'm not sure FileData and the Elf stuff should be the same class.
I just did a truthy check.
And I don't like temp_var, where a descriptive variable name can be used
Well, I was trying to make fun of tom marvolo fiddle.
mhm, I also didn't use split, just checked for \n instead
by using inheritance
ig
tbh, I know some list comprehension and map function but I don't feel comfortable enough to use it for a one liner to replace my current function yet.
U dont even need to use an else. if non equal check.
U can do a truthy check
Its a bit cleaner
I did ```py
def parse_file(path: str) -> list[list[str]]:
with open(path) as file:
return [elf.split("\n") for elf in file.read().split("\n\n")]
def part_one() -> int:
data = parse_file('day1.txt')
calories_per_elf = [[int(calories) for calories in elf] for elf in data]
total_calories_per_elf = [sum(calories) for calories in calories_per_elf]
return max(total_calories_per_elf)
def part_two() -> int:
data = parse_file('day1.txt')
calories_per_elf = [[int(calories) for calories in elf] for elf in data]
total_calories_per_elf = [sum(calories) for calories in calories_per_elf]
return sum(sorted(total_calories_per_elf)[-3:])
print(part_one(), part_two())```
as a hasty solution
Uhm, not quite sure what you mean by that ;-;
one day ill get to the level where my hasty solutions come with type hints ๐
bro what ๐ญ
They've become second nature after a while.
I'm just curious, how does this snippet work:
return [elf.split("\n") for elf in file.read().split("\n\n")]
asking because for whatever reason it returns [['']] for me and I'm super confused on why on earth I get that
It first splits the whole file into many strings which look like
19389\n12848\n128489
Then it splits these strings by \n to create a list of lists
I also got an empty string which was because of an EOF newline for me
hmm, but why does it return [['']] in my case for this snippet ?
mh
but shouldn't the test var be unaffacted ?
That looks like it should work to be honest
kk
mhm, for the txt file I just copied it off the website
You sure the file looks right
Hey @sage sentinel!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
readlines() reads the whole file and moves the cursor to the end. So read() isn't going to have anything to read
ohhhhh
Oh right yeah this is true ^ Forgot about that
I didn't even know about that ๐
https://github.com/DJJ05/AOC2022/tree/main/1 Hopefully we keep up with the whole month ๐
Alright thank you, good to know I'm not completly stupid yet
laughs in bad code in github only cba to write one-liners if it's not really necessary idk
Thats what makes it fun for me tbh
Are one-liners actually used that much in like production code and stuff ?
I mean, I use them where I can but for some cases I prefer to not do that
Small ones yes
If theyre unreadable then no
ideally, no. At least nothing complex or cursed
Is something like this considered small or is this overkill ?
Overkill
just curious so I don't end up writing horrible code when working on production projects. ๐
That wouldn't be used in production
Wouldn't pass code review
You can't tell what it's doing without figuring it out with a decent bit of effort
mhm, fair point
Anyone looking at that won't know its summing elf calories and printing the top 3 elves
I mean, looks neat but ye, hard to read
for me it's about participating and trying my best I guess, just started coding in general like 1 year ago and still fairly new to list comprehension and stuff so I try to use it where I can
What's with the coding=? Are you using python 2?
๐
Just an FYI, the AoC creator prefers if you don't share the inputs online. Best not to commit/push the 'input.txt' files
Ah okay thanks I'll get rid of it
Is that just because theyre behind an authentication wall?
It's mostly cos the different inputs are one of the ways to stops others just stealing his puzzles
9 votes and 18 comments so far on Reddit
Ah I see, thanks !
I have input.txt in my gitignore to prevent it happening
Yeah added it now also
this year storing cache in home directory
Don't keep cache around at home, it rewards burglars.
wait is that actively discouraged?
yes indeed
hmm didn't know about that
pandas rocks
pd.read_csv("day_1.input", skip_blank_lines=False, header=None, squeeze=True).pipe(lambda s: s.groupby(s.isna().cumsum()).sum().convert_dtypes()).nlargest(3).pipe(lambda r: (r.iat[0], r.sum()))
cumsum :)
yeah people joke about that every now and then :|
๐ญ
Thats really cool tho
Data science is a part of python I never really work with
wouldn't it be easier to come up with a generator than reverse engineering the whole thing by farming inputs from random github repos?
doesn't make sense to me
some inputs might be easy to generate (like todays) but others you'd need to check that the input you generate isn't an invalid input for the problem
def day1(inp: str) -> tuple[int, int]:
ls = []
for i in inp.strip().split("\n\n"):
val = sum(int(j) for j in i.split("\n"))
ls.append(val)
ls.sort(reverse=True)
return (ls[0], sum(ls[0:3]))
yes, I know it's bad, but at least it's readable
I think it looks good. Minor point I'd make is that shadowing the input function isn't the best thing to do, but here doesn't really matter much
yep, ima change it
or you could get items from the back without changing the sort order
my single line solution to part 1: max([sum(list(map(int, i.split("\n")))) for i in a.split("\n\n")]) Where a is the string copied from the page
unnecessary [] and list()
Oh yeah, the list is probably unnecessary
:0 It actually works without square brackets, I didnt expect that.
Yeah, max will work on any iterable that has comparable items in it, not just lists
That makes sense, sum and the other operators that I excepted to work only for list work probably too, right?
yes
That's cool. I've never seen any python tutorial so I don't know many tricks that could save space and time.
Thanks
Hello!
Tad longer solution but elegant I think 
https://github.com/Achxy/AoC-2022/blob/main/source/day_1.py
tad longer
one line with list comp
https://github.com/Achxy/AoC-2022/tree/main/source/advent/data
Try not to commit/push the input files - the AoC creator would prefer you didn't do that
Advent of Code 2022 - https://adventofcode.com/2022 - AoC-2022/source/advent/data at main ยท Achxy/AoC-2022
By watching this forum for 2 minutes I learned 2 new things already, the nlargest function is awesome
class Solution(AdventSolution, day=1)
never seen a class declaration like that before 
Not sure why but sure I would add that to my gitignores 
10 votes and 18 comments so far on Reddit
It's fun to do some metaprogramming trickery once in a while ๐
that inheritance automatically instantiates the derived classed and runs the part_1 and part_2 if (and only if) the program is being run as top level file :D
we can not mention day altogether and opt out of this
:o what an interesting framework you made there @pure lotus
Thanks :D
Duly removed ๐
Oh, didn't know that. I have done that for what I have done so far in AOC.
Guess I may need to make a new repo to support this
Guess I may need to make a new repo to support this
you can just delete the files in your remote repository?
no it isn't necessary
or are you talking about .git containing your history?
i read more into the thread and it isn't exactly actively enforced, partly why you almost never hear about it
you can change history if you want to
just add them to gitignore and call it a day, no need to create a whole new repo/purge
If you delete it, then you still have years of commits where it can all still be found
used nim heapQueue instead of sorting:
import std/[heapqueue, sequtils, strutils]
import nimpy
proc nlargest[T](iterable: openArray[T], n: int): HeapQueue[T] =
for i in iterable:
if result.len < n:
result.push i
elif i > result[0]:
discard result.replace i
let CALORIES = "aoc_lube"
.pyImport
.callMethod(string, "fetch", 2022, 1)
.split("\n\n")
.mapIt(it.split.map(parseInt).foldl(a + b))
echo "Part 1: ", CALORIES.max
echo "Part 2: ", CALORIES.nlargest(3).foldl(a + b)
#part 1
with open('advent1.txt', 'r') as file:
food_totals = []
contents = file.read().strip().split('\n\n')
for elf in contents:
counts = elf.split('\n')
makeint = lambda x: int(x)
intcounts = list(map(makeint, counts))
food_totals.append(sum(intcounts))
food_totals.sort(reverse=True)
print(food_totals[0])
#part 2
print(sum(food_totals[:3]))
Beginner here. You guys' one-liners are most impressive. It seems for the most part I used the same logic as you guys though that's cool.
Unless I don't know of a way to do it
you can rebase in git
Nice!
instead of makeint = lambda x: int(x) you can directly pass int as the first argument to map
like intcounts = list(map(int, counts))
oooh okay thank you.
I'm often guilty of this
In my defence it's usually at 5am
it's 2:15am here
And sometimes I think I need to do extra processing on it
my solution for Part 2 has extremely horrible time complexity
because I wanted it to be functional and have no state
behold
.split("\n\n").map(e => e.split("\n").reduce((a,c)=>a+ +c,0)).filter((e,_,a)=>e==Math.max(...a)||e==Math.max(...a.filter(z=>z!=Math.max(...a)))||e==Math.max(...a.filter(z=>z!=Math.max(...a)&&z!=Math.max(...a.filter(z=>z!=Math.max(...a)))))).reduce((a,c)=>a+c)
``` (JS)
takes like four seconds but gets the job done
this calls Math.max (which probably iterates over every elf or nearly every elf) 13997279 times on my input
๐
this is what I call "functional programming"
I sure do love JS!
don't get me wrong, it's not bad code because it's JS or because it's functional
it's bad code because I wrote it
d1p1โโ/+/ยจ
d1p2โ{+/3โ{โต[โโต]}+/ยจโต}
is that APL
yea
nice!
I'll do selected days
not all of them since it won't be fun
rest can be other langs
I'll try to do as many days as possible, but I'm not going for leaderboard/speed, I'm going for most cursed code on my first try (the rule I set for myself is that I have to go with the first code I write that solves the problem, so I'll try to delay that until my code gets as cursed as possible)
with open("day1.txt",'r') as f:
k = f.read().split('\n\n')
p = []
for i in k:
g = i.replace('\n',' ')
l = g.split()
x = []
for i in l:
x.append(int(i))
p.append(sum(x))
print(max(p))```
ik it's not the best
but it was fun to see that I am not really good at using my knowledge
XD
Is it just me or
If using O(k) memory, it's not possible to do better than O(kn) worst case time?
where k is the number of top (3) and n is the total number of all elves
In other words if nlgn < kn then one should just do a sort on the sums
Though under sorting all of the sums requires O(n) memory, which is clearly a lot greater
All we need is copilot https://github.com/muellerzr/advent-of-code-2022/blob/main/day_1/01_12.py
like last year, I decided to just write my solutions directly in the terminal, as one-liners
d1a = max(sum(map(int, substr.split())) for substr in in1a.split("\n\n"))
d1b = sum(sorted(sum(map(int, substr.split())) for substr in in1a.split("\n\n"))[-3:])
sadly, it isn't the best when it comes to memory, as I had to sort for second half
What's better for memory
keeping only top 3 elves. right now I calculate them all and sort them to get top 3. but that's impossible to do in a single line
okay, found it, python implements heaps in standard library
so it's doable
import heapq
d1b = sum(heapq.nlargest(3,(sum(map(int, substr.split())) for substr in in1a.split("\n\n"))))
now it's perfect
oh, wait
does it construct a whole heap? if yes, this would only help with time complexity (takes only 3 things from the heap) but not memory
Don't you need to calculate all to get top 3?
it'll take more memory to store the input string ๐
you need to calculate all, but you need to only keep 3 as you go. you can drop elves that aren't top 3
... right XD
if you already have elves that hold 4 5 6, then encounter an elf who only holds 1, you don't have to keep that one, your top 3 don't change
Rust
why does your timing have days ๐คจ
you'd hope it did
it actually took about ~8^-6 days
Seeing all these elegant solutions and here I am doing a bunch of for loops and list operations ๐ฅต
oh damn i shouldve taken the input as the provided file ๐
planning for tmr code to be better
mainly the 2nd part with using sorted
and abusing stream api
wait lmao just realised all code there is python
im just different
calculates aoc answer in ~8^-8 days
mind. blown.
you should implement weeks and months and years
remove print for faster execution (real)
I misspelled elves at the begging and I am too lazy to fix it, for the rest of AOC I will call them elfs
๐
elevens
a
๐
just remove any newlines
ez
yay done
now to one line it
did discord roll out their new font?
because backticks are ugly now
here's pretty much what I did for python ```py
calories = [[int(n) for n in lines.split("\n") if n] for lines in input_data]
summed = sorted([sum(i) for i in calories], reverse=True)
where input_data was f.read().split("\n\n")
i was thinking text looked a bit strange
yeah haha
I did a similar thing for rust, but the result was longer
now to write a helper tool
There was some info on my phone discord app some time ago about new font incoming in some time
Yep
I find it extremely ugly
My opinion though. Others might like it.
so it wasn't just me?
No
haha
I wish I kept discord open and didn't turn off my computer ๐ญ
i think the decorator is being too cute
with open('day1.txt', 'r') as f:
s = f.read()
b = []
fl = []
v = s.replace('\n\n','break').split('break')
for i in v:
a = i.split('\n')
for e in a:
b.append(int(e))
fl.append(sum(b))
b.clear()
#Pt1
print(sorted(fl)[-1])
#Pt2
print(sum(sorted(fl)[-3:]))```
This is my solution for day one, I know it's not optimal at all, I've seen someone do it with one line. But I'm quite new to Python so I'm happy with it, if anyone has any straight-forward improvements I can make then I'd love to hear them
usually i let the file close as soon as i'm done reading it:
with open('day1.txt', 'r') as f:
s = f.read()
do_other_stuff()
The thing I notice - why replace \n\n with break and then split on break?
additionally, you can just do f.read().split("\n\n")
instead of replacing with a break
Ah yeah good idea
I'd also give your variables more descriptive names
You also only need to sort fl once
Honestly I don't remember, I think in my original plan for a solution that was necessary but it's not anymore
but decorators for solutions makes more sense to me
the idea for the input is that the handler could transform it in whatever way you need
yeah, but you can transform the raw string in whatever way you need
mm, fair enough
what if I have decorators for both the solution and the input >.>
decorators all around
i like the idea of :
@submit(year=2022, day=1, part=1)
def my_solution():
...
yeah, I had that kind of thing in mind for solutions too
i mean the input handler could just be:
def input_handler():
return do_something_with(raw_input(year=2022, day=1))
hmm, yeah, I could swap out the decorator with just fetching the input with a helper
ooh, one thing that the decorator could be nice for is injecting the handled input into the solutions
might be too indirect
@input_handler(day=blah, year=blah)
def handle(raw_data):
blah
@solution(day=blah, year=blah, part=blah)
def solution(input_data):
blah
``` where the result of `handle` is passed to `solution` automatically, kind of like dependency injection
there's a lot of times where just keeping the raw input as something you can transform on one line will be easiest
yeah, I guess that's fair - it was a similar case with today
i started looking at printing the examples in the problem descriptions, but i don't know if it's more useful than just scrolling down on the page
my aoc helper last year had a testing feature where it tested it with example data
it worked most of the time
from the challenge
I think I'll switch out the decorator for just some get_input helper, thanks for the input!
I'll keep a decorator for the solution though >.>
./day1 0.00s user 0.00s system 16% cpu 0.023 total. using time on mac, does it mean it ran in 0.023 seconds?
how are the scores calculated
who finished first
definatly not gonna make it ๐
same bro
i feel like the decorator would be cool to have for more simple transformations where it can understand the return annotation and transform the data in tha tway
that
someone posted a 1 liner GG
does AoC get gradually harder or no
the later days are harder, yeah
it does
shit
and if you don't want it to get transformed, just pass in an argumnt
argument
wait till u need 3hrs to get answer
stick with it! Challenges are nice :p
this could just be a separate transform function
rust-analyzer doesn't workwith single file projects so 90% of my time was reading compiler errors
fair enough
if u don't use some algorith that is
which could be cool if it was general enough
transform(raw_input, np.array, (3, -1))
ooh
cooool
i might try and give a go at a more general transform annotation for my helper
but i usually do this with a combination of extract_ints, chunk and np.array
i think i could make it general
what was yoursolution or algorithm for part 1?
doesn't it? It'll work fine if all you have is a main.rs
(I do mean one generated by a cargo new, though)
I read all of the file with inputs, split it by \n\n, and then added each section up and appended it into a vector, then printed out the Vector's max()
yeah, i didn't do that
do that!
new = calories_list.replace("\n\n",'break')
new_new = new.split('break')
def sum(num)-> int:
sum = 0
real_num = ''
for i in num:
if i != '\n':
real_num += i
if i == '\n':
sum += int(real_num)
real_num = ''
sum += int(real_num)
return sum
max_L = []
for i in new_new:
max_L.append(sum(i))
max_L.sort()
summ = 0
for h in max_L[-3:]:
summ += h
print(summ)```
๐ญ
but them i need one for every day...
i kept getting weird answer
use std::fs;
fn main() {
let input = fs::read_to_string("input.txt").unwrap();
let list_of_inputs = input.split("\n\n");
let mut cal_total_list = Vec::new();
for cal_list in list_of_inputs {
let mut total: i32 = 0;
for cal in cal_list.split("\n") {
total = total + cal.parse::<i32>().unwrap();
}
cal_total_list.push(total);
}
let mut best_3 = 0;
for _ in 0..3 {
let max = cal_total_list.iter().max().unwrap().clone();
best_3 = best_3 + max;
cal_total_list.retain(|&x| x != max);
}
println!("{}", best_3);
}
that's not terrible, I have a folder for every day anyways
meh
i'll just keep running cargo check
i mean rustc
been webdeving these past months and i'm so rusty in python ๐ฅด wtf did i just write```py
with open("./input.txt") as file:
input = [
[line.rstrip() for line in elf.split("\n")]
for elf in file.read().split("\n\n")
]
calorie_sums = [sum(int(line) for line in elf) for elf in input]
print(max(calorie_sums))
oh god, i mentioned rust, aboo's gonna strike anytime now
its actually good
HI THERE
hello
HAHAHAHAH
i updated my nim solution
include aoc
let CALORIES = fetch(2022, 1).split("\n\n").mapIt(sum it.extract_ints)
part 1: CALORIES.max
part 2: sum CALORIES.nlargest(3)
so nice and pretty
if you squint, it looks like compiled python
meh
you're meh
which language do you transpile to
c
good
not much reason to compile to javascript unless you have some web application in mind or need js packages
probably compatibility reasons
I suppose so
omg it's salt :O
๐ฏ
can't wait to look over your code during the next 24 days and levitate in ecstasy every time
(assuming you're still pythoning, of course lol)
yep, python solutions are my primary ones
day 1 solution was:
from heapq import nlargest
import aoc_lube
from aoc_lube.utils import extract_ints
CALORIES = [
sum(extract_ints(elf))
for elf in aoc_lube.fetch(year=2022, day=1).split("\n\n")
]
def part_one():
return max(CALORIES)
def part_two():
return sum(nlargest(3, CALORIES))
aoc_lube.submit(year=2022, day=1, part=1, solution=part_one)
aoc_lube.submit(year=2022, day=1, part=2, solution=part_two)
this was the most difficult so far ๐
calories = ""
with open("1.txt") as f:
for i in f:
calories += i
calories = calories.replace("\n\n", " ")
calories = calories.replace("\n", " ")
calories = calories.split(" ")
values = []
for i in calories:
x = 0
n = i
n = n.split(" ")
for j in n:
x += int(j)
values.append(x)
values = sorted(values)
print(f"Part 1:{values}")
#Part 2
x = values[-1] + values[-2] + values[-3]
print(x)
my very humble solution to the problem
nice
I tried to do modulo arithmetic for p2 but failed pretty badly so fell back to checking explicit pairs of moves/move+outcome like a chump
i blame it on being early morning
anyway, here's my code
Day 2?
#1048103002986254387
oh shit my bad
I wrote here about my day 2 solutions as well, but I since moved XD
gone now. Yeah, it's really early morning for me lol
Last year everything was in one channel, so it's kinda confusing
9am being early XD
10am and same~
I don't function properly at that hour
it's just jarring
Anyway you can share everything?
From aoc_helper.fetch(1, 2022) to mapped to extract ints?
Thanks
aoc_helper is on pypi and provides extract_ints
(as well as a custom list)
Just making sure I have the right one.
https://pypi.org/project/aoc-helper/
Asking because there is no extract_ints or custom list.
Thanks again
That's the one and yes there definitely is
from aoc_helper import list, extract_ints
Thank you. I'll look at the source code to see everything it has
If you install it with the cli optional deps you can have it generate templates for you
It imports most of the stuff lol
aoc template
Oh nice. Thanks for that info
:o what's so nice about the aoc_helper list?
# aoc problem 1
import re
def top(n, lst):
sorted_lst = sorted(lst, reverse=True)
acc = []
for x in sorted_lst:
if len(acc) >= n:
break
if len(acc) == 0 or x < acc[-1]:
acc.append(x)
return acc
def solution():
with open('1.txt') as f:
acc = [0]
for line in f:
match_num = re.match(r'(\d+)\n?', line)
match_empty = re.match(r'\n', line)
if (m := match_num):
acc[-1] += int(m[1])
elif match_empty:
acc.append(0)
print(max(acc)) # solution a
print(sum(top(3, acc))) # solution b
if __name__ == '__main__':
solution()
Interesting you used regex. If you do a split over the whole text on \n\n you shouldn't need to involve re
# aoc problem 1
def solution():
with open('1.txt') as f:
acc = []
for block in f.read().split('\n\n'):
lines = block.splitlines()
acc.append(sum(int(l) for l in lines))
acc = sorted(set(acc))
print(acc[-1]) # part 1 solution
print(sum(acc[-3:])) # part 2 solution
if __name__ == '__main__':
solution()
nice :)
AoC 2022 | Day 1 | Solutions & Spoilers
Wonder if it's a speed thing
What's iu.n_max?
a custom function that gets the n highest values in an iterable
ye
cool
!d heapq.nlargest this already exists
heapq.nlargest(n, iterable, key=None)```
Return a list with the *n* largest elements from the dataset defined by *iterable*. *key*, if provided, specifies a function of one argument that is used to extract a comparison key from each element in *iterable* (for example, `key=str.lower`). Equivalent to: `sorted(iterable, key=key, reverse=True)[:n]`.
it does, but I have variants such as n_minmax and n_argmin so I group it in with the rest
def part_one():
puzzle_input = utils.get_puzzle_input(day="one")
return max([sum(map(int, elf.split("\n"))) for elf in puzzle_input.split("\n\n")])
def part_two():
puzzle_input = utils.get_puzzle_input(day="one")
return sum(sorted([sum(map(int, elf.split("\n"))) for elf in puzzle_input.split("\n\n")])[-3:])
These are what I came up with, it's cool to see everyone's different solutions
Hm. That looks like mine. Except that I used split without parameter.
elfs = sorted((sum(map(int, elf.split())) for elf in open('input.txt').read().split('\n\n')), reverse=True)
print(elfs[0], sum(elfs[:3]))```
๐
sum_cals = []
with open('input.txt', 'r') as in_txt:
seq = in_txt.read().splitlines()
result = [
[int(string.rstrip()) for string in group]
for key, group in groupby(seq, lambda s: s != "")
if key]
for line in result:
sum_cals.append(sum(line))
print(max(sum_cals))
print(sum(sorted(sum_cals)[-3:]))```
My suggestion, do an initial split on \n\n. You shouldn't need groupby then
with open('input.txt', 'r') as in_txt:
seq = in_txt.read().split("\n\n")
sum_cals = [sum(int(snack_cals) for snack_cals in inventory) for inventory in [line.splitlines() for line in seq]]
print(max(sum_cals))
print(sum(sorted(sum_cals)[-3:]))
Thanks for the tip, thatโs much better. Doing this on my phone at work (I have a do-nothing third shift job) is a pain lol
oof rip - well done for coding this on your phone!
Thanks, hoping I donโt have an RSI by the end of the month
#Advent of code day 1
#Problem 1
#--- Day 1: Calorie Counting ---
with open('aoc22_1.txt','r') as inp: #giving the input as text file
inp1 = inp.read()
str1 = str(inp1) #converting the input in string
li1 = str1.split("\n") #making a list from the string
#Code that does the main work
#Making a List consist of other lists
main_list = []
temp_list = []
for i in range(len(li1)):
try:
temp_list.append(int(li1[i]))
except ValueError:
main_list.append(temp_list)
temp_list = []
main_list.append(temp_list)
main_list.pop()
#Main list is now complete
#Now creating a list which will consist of the sum of those lists in the Main list
li2 = []
for j in main_list:
li2.append(sum(j))
#How many Elf there is
HowManyElf = len(li2)
#Which elf is carrying the most
MostCarryingElf = li2.index(max(li2))+1
#The Max sum is the answer
MostCaloriElf = max(li2) #Answer of part 1
li2.remove(max(li2))
SecondMostCaloriElf = max(li2)
li2.remove(max(li2))
ThirdMostCaloriElf = max(li2)
TotalTopThree = MostCaloriElf+SecondMostCaloriElf+ThirdMostCaloriElf
ans = MostCaloriElf,TotalTopThree
with open('aoc22ans_1.txt','w') as out:
print(ans,file=out)
Tried it with text format input and also used comment so everyone can understand so easily
I hope this code will help beginners
Also did some extra thing that the problem didn't ask but is interesting
Would you be open to comments about your code?
yeah sure! But my code is horrible and it's rather embarrassing. for example, I could've just used the sort() function and used indexing in the list and easily find the top 3 big numbers but instead, I removed the max from the list and kept using the max() function
I think this is what happens when you start coding again after 2 years
Hey, if your code works, thatโs the most important thing!
yeah true ๐
That said, yes, you could sort it and index/slice to get what you need
That was one comment I was going to make
The other one is regarding the initial parse
like the names of the variable?
If you split by \n\n first then you can split the input into their initial groups
ohh yeah
Then for every list element you can do a further split by \n
A list comprehension is the easiest way to do this
That way, you get your list of lists in a much easier way
yeah you know i actually did the try and except just for fun! thanks for the information anyway
Ok , no worries :)
i just realized how bad i am at programming and it's a good thing to know
because now i know how to improve
took me literally 40 mins or so just for the first part, but the second part took 30 seconds or something
here's my solution ig/
not the most beautiful and also i had to do manual work to find the biggest one because i was so frustrated that i decided i'll do the finding part manually
i did python3 main.py > finally.txt && vim finally.txt
in vim i did :sort G and there it was
@prime jolt can u comment my code i wanna see where i can do better
i hadn't processed this kind of data before lol it was really annoying
sheeesh ๐ฅต
i yield because return breaks my code for some reason
now it doesn't
so what I did, at least, was take everything in the raw input and turn it into a list of lists - that's what you have with loop. What you could've done from there is turn that into a list of integers, with each integer being the sum of every nested list inside your original list of lists, and then sort it - that way, you can get the top value for part 1, and the top 3 values for part 2
Now I do
i could passed the sorted function instead of doing it in vim too
def part_1(input_data: list[str]) -> list[int]:
calories = [[int(n) for n in lines.split("\n") if n] for lines in input_data]
summed = sorted([sum(i) for i in calories], reverse=True)
return summed
``` was my solution
that's so good. that's jsut awesome
then summed[0] for the first part, and summed[:3] for the second
lol, you should see some of the one-liners people come up with
i have a question for part 2
do we have to calculate the whole thing?
ike the whole file
๐ฅถ
yes
print(*(v:=sorted(map(lambda s: sum(s), map(lambda x: map(int, x.split("\n")), open("inp.txt").read().split("\n\n")))),v[-1],sum(v[-3:]))[1:])
``` my part 1 and 2 solution
super idol
Here's my solution to parts 1 and 2
with open('input.txt', 'r') as file:
data = file.read().split("\n")
print(data)
totalCalories = 0
totalCalorieList = []
for line in data:
if line == '':
totalCalorieList.append(totalCalories)
totalCalories = 0
else:
totalCalories += int(line)
totalCalorieList.sort()
largestCalorieCount = totalCalorieList[-1]
topThreeCalorieCount = totalCalorieList[-1] + totalCalorieList[-2] + totalCalorieList[-3]
print("The largest amount of calories is " + str(largestCalorieCount))
print("The combined total of the amount of calories that the top three calorie having elves have is " + str(topThreeCalorieCount))
I've only now realized how bad it is looking at all the other solutions
Any tips on how I can shorten it/make it more efficient?
There are no bad solutions in AoC.
Looks around and see what other people did.
For example I split on blanklines instead of each newline.
not necessarily an efficiency thing, but you can note that things like if line == '' can be shortened to if not line
and your totalCaloriesList[-1] + totalCalorieList[-2]... could be a sum over totalCalorieList[-3:]
Ok, thank you for the feedback
Should probably brush up on some of the implicit syntax like "if not line"
๐
yeah idk why I did split("\n")
Trying to get back into coding again but trying to step away from OOP and doing everything functional (I aim to practice serverless functional scripting). It was a rough start with day 1. Solution here for anyone interested: https://github.com/Qoyyuum/adventofcode/tree/main/2022/day01
FYI - the author of AoC would prefer you to not upload the input files to GitHub.
do it in Haskell now
just create a gitignore and remove the input file too
I didn't know that at all. I'll remove it. Thanks!
Parsing -
calories = [sum(map(int, i.split("\n"))) for i in INPUT.split("\n"*2)]
Part 1 -
result = max(calories)
print(result)
Part 2 -
top3 = sorted(calories)[-3:]
print(sum(top3))
wth 3 liners? i took like 200 lines ๐ถ
ayy i got my first star :D
