#AoC 2022 | Day 1 | Solutions & Spoilers

1604 messages ยท Page 2 of 2 (latest)

wary bough
#

but you could use the last 3 values in sorted(elves) to get the max value

bold bear
#

Literally just does the task and isnt hard coded.

wary bough
#

why the function

bold bear
wary bough
#

where do you reuse it in the file

bold bear
#

I feel like, you guys are the type of people to set up a base class and use polymorphism for this type of thing

bold bear
violet hound
bold bear
wary bough
bold bear
#

If u did that, I would have literally quit coding.

violet hound
#

I end up copying and pasting my read file function quite a lot between days

violet hound
#

was considering just doing a base class or mixin to bring it in

quartz summit
#

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

covert sage
#

I like doing it each time since it lets you customise how you parse your input each time

violet hound
#

Yeah, that's the reason I decided not to

covert sage
#

some days will all be the same, but having a solution-specific one can clean up the rest of your code

violet hound
#

that plus I like being able to copy paste the whole solution somewhere

wary bough
#

i just copy and paste and formulate solutions in the REPL

covert sage
#

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

cunning plume
#

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

frail rivet
#

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]
spice jungle
#

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)
willow marlin
#

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
willow valve
spice jungle
golden narwhal
#

windows & HTTP newlines use \r\n, you'll rarely see it elsewhere

toxic oar
#

i miss 2021 where i onelined like 4 days with numpy

golden narwhal
#

then you should try APL ๐Ÿ˜„

toxic oar
#

or alternatively k

golden narwhal
#

but my pretty glyphs ๐Ÿ˜ญ

toxic oar
#

no pretty glyphs for you โŒ

willow valve
willow valve
golden narwhal
#

That's true as well

spice jungle
golden narwhal
#

anything to avoid ansi escapes BABAXD

gleaming cave
#

okay

#

i need some help

#

i got the first one right

#

but the secound one is giving me a lot of problems

violet hound
gleaming cave
#

i've tried a bunch of diffrent ways to get the top three but i always get the same number 203454

frail rivet
#

What is this channel for? Is it a special event or something?

spice jungle
oak idol
#

๐Ÿป

spice jungle
violet hound
keen flickerBOT
#
What is Advent of Code?

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.

How do I sign up?

Sign up with one of these services:

Auth Services

GitHub
Google
Twitter
Reddit

How does scoring work?

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.

Join our private leaderboard!

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.

gleaming cave
#

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:]))
clear river
#

It's a bit... verbose

gleaming cave
#

?

clear river
#

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:]))
gleaming cave
#

what should i input for data

#

?

clear river
#

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

gleaming cave
#

okay, that worked

#

i still dont understand why my code dosen't work

#

thanks

clear river
#

You may be overthinking it.

#

don't worry about the max first. Just calculate how many calories each elf is carrying

stable goblet
#
# 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

gleaming cave
#

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
lilac niche
#

how does if line.strip() work

clear river
#

it remove whitespace surrounding a string

gleaming cave
#

line.strip removes the newline char. if a line is just a newline then it is basically blank

clear river
#

basically checks if it isn't blank

lilac niche
#

oh

rain forum
stable goblet
#

eh mine's shorter

rain forum
#

map(int, ) is so smart lol

#

i never through of that

stable goblet
#

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]))

bold bear
#

@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)
rough orchid
#

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]))
violet hound
#

super is not needed though

rough orchid
#

Bit clunky

bold bear
violet hound
bold bear
#

Are u proud of me?

bold bear
bold bear
violet hound
bold bear
violet hound
#

You aren't changing it, so you can get rid of the __init__ in the subclass

rough orchid
#

I hate this font, btw

bold bear
#

I just used splitlines and split it until i got the blank line. and then u checked if there was a blank line shrug

#

then appended to a list

violet hound
# bold bear Whats that?

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

rough orchid
#

Was gonna use splitlines but didn't wanna have to rejoin them again

#

I love list comps

violet hound
#

^ this was my unit tests for today

rough orchid
#

They look so nice

violet hound
#

So if you were to change or enhance your code, you can run the tests to check that you didn't break anything

bold bear
rough orchid
#

For me the challenge is making it work on one line without any kind of signpost variables or stuff like that

violet hound
#

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

rough orchid
#

I like them like that

bold bear
#

I see.

rough orchid
#

My code kept failing because the input had a newline EOF

bold bear
#

Tho idek why someone used a generator for this.

rough orchid
#

Monkeypatched the input ๐Ÿ™ˆ

bold bear
#

I saw someone code a generator just for part 1 ๐Ÿ’€

rough orchid
#

๐Ÿ˜ญ

bold bear
#

I forgot what does [:3] do?

simple jetty
#

First 3 elements

bold bear
simple jetty
#

But they couldve not used reverse, and done [-3:] instead

rough orchid
#

Sum works on map which I overlooked

#

Removed 6 characters

bold bear
rough orchid
#

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]

bold bear
#

Ah

bold bear
# rough orchid Equivalent to `i = [int(item) for item in i]`
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
simple jetty
rough orchid
#

Ahh yeah you're right saves me some more ๐Ÿ‘

bold bear
#

@simple jetty how would u rate the code?

rough orchid
#

True one liner now

sage sentinel
#

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 ๐Ÿ˜„

bold bear
sage sentinel
sacred spoke
#

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.

bold bear
simple jetty
bold bear
#

I just did a truthy check.

simple jetty
#

And I don't like temp_var, where a descriptive variable name can be used

bold bear
sage sentinel
bold bear
#

by using inheritance

sage sentinel
# bold bear holy

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.

bold bear
#

U can do a truthy check

#

Its a bit cleaner

simple jetty
#

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

sage sentinel
proper musk
#

one day ill get to the level where my hasty solutions come with type hints ๐Ÿ˜†

bold bear
simple jetty
sage sentinel
rough orchid
#

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

sage sentinel
rough orchid
#

Because you're using readlines() and not read()

#

Oh nvm

#

My bad misread

sage sentinel
rough orchid
#

That looks like it should work to be honest

sage sentinel
sage sentinel
rough orchid
#

You sure the file looks right

sage sentinel
mossy tulipBOT
#

Hey @sage sentinel!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

rare owl
rough orchid
#

Oh right yeah this is true ^ Forgot about that

sage sentinel
#

I didn't even know about that ๐Ÿ˜…

rough orchid
sage sentinel
#

Alright thank you, good to know I'm not completly stupid yet

sage sentinel
rough orchid
#

Thats what makes it fun for me tbh

sage sentinel
#

Are one-liners actually used that much in like production code and stuff ?

sage sentinel
rough orchid
#

If theyre unreadable then no

rare owl
sage sentinel
#

Is something like this considered small or is this overkill ?

rough orchid
#

Overkill

sage sentinel
#

just curious so I don't end up writing horrible code when working on production projects. ๐Ÿ˜…

rough orchid
#

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

sage sentinel
#

mhm, fair point

rough orchid
#

Anyone looking at that won't know its summing elf calories and printing the top 3 elves

sage sentinel
#

I mean, looks neat but ye, hard to read

rough orchid
#

Yeah that's what its about for me

#

Its efficient and compact

sage sentinel
clear river
rough orchid
#

It's my code

#

And no I just put it there anyway

sage sentinel
#

๐Ÿ˜‚

#

stealing code without stealing it ๐Ÿ˜‚

rough orchid
#

๐Ÿ˜‚

violet hound
rough orchid
#

Ah okay thanks I'll get rid of it

#

Is that just because theyre behind an authentication wall?

violet hound
#

It's mostly cos the different inputs are one of the ways to stops others just stealing his puzzles

rough orchid
#

Ah I see, thanks !

violet hound
#

I have input.txt in my gitignore to prevent it happening

rough orchid
#

Yeah added it now also

brittle jasper
#

this year storing cache in home directory

simple jetty
#

Don't keep cache around at home, it rewards burglars.

sour marsh
violet hound
#

yes indeed

sour marsh
#

hmm didn't know about that

solar yew
#

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()))
rough orchid
#

cumsum :)

solar yew
#

yeah people joke about that every now and then :|

rough orchid
#

๐Ÿ˜ญ

#

Thats really cool tho

#

Data science is a part of python I never really work with

sour marsh
#

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

violet hound
#

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

opaque moat
#
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

violet hound
#

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

solar yew
#

nice indeed

#

BTW you can pass reverse=True to .sort

simple jetty
#

or you could get items from the back without changing the sort order

digital orbit
#

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

simple jetty
#

unnecessary [] and list()

digital orbit
#

:0 It actually works without square brackets, I didnt expect that.

simple jetty
#

Yeah, max will work on any iterable that has comparable items in it, not just lists

digital orbit
#

That makes sense, sum and the other operators that I excepted to work only for list work probably too, right?

simple jetty
#

yes

digital orbit
#

That's cool. I've never seen any python tutorial so I don't know many tricks that could save space and time.

#

Thanks

pure lotus
#

Hello!

toxic oar
#

tad longer
one line with list comp

violet hound
digital orbit
violet hound
#
class Solution(AdventSolution, day=1)

never seen a class declaration like that before pithink

pure lotus
pure lotus
#

we can not mention day altogether and opt out of this

toxic oar
#

:o what an interesting framework you made there @pure lotus

pure lotus
#

Thanks :D

light valley
pure lotus
pure lotus
#

or are you talking about .git containing your history?

sour marsh
#

i read more into the thread and it isn't exactly actively enforced, partly why you almost never hear about it

pure lotus
#

you can change history if you want to

sour marsh
#

just add them to gitignore and call it a day, no need to create a whole new repo/purge

light valley
#

If you delete it, then you still have years of commits where it can all still be found

brittle jasper
#

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)
long summit
#
#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.

light valley
#

Unless I don't know of a way to do it

pure lotus
pure lotus
#

like intcounts = list(map(int, counts))

tribal bear
#

In my defence it's usually at 5am

pure lotus
#

it's 2:15am here

tribal bear
#

And sometimes I think I need to do extra processing on it

pure lotus
#

can't fall asleep

modern mason
#

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

golden narwhal
#
d1p1โ†โŒˆ/+/ยจ
d1p2โ†{+/3โ†‘{โต[โ’โต]}+/ยจโต}
modern mason
#

is that APL

golden narwhal
#

yea

modern mason
#

nice!

golden narwhal
#

I'll do selected days

#

not all of them since it won't be fun

#

rest can be other langs

modern mason
#

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)

frail rivet
#
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

velvet epoch
#

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

kindred atlas
woven isle
#

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

woven isle
#

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

kindred atlas
golden narwhal
#

it'll take more memory to store the input string ๐Ÿ˜„

woven isle
woven isle
hard mason
candid obsidian
#

why does your timing have days ๐Ÿคจ

hard mason
#

windows

#

my code took 0-days to run

golden narwhal
#

you'd hope it did

hard mason
#

it actually took about ~8^-6 days

lofty kettle
#

Seeing all these elegant solutions and here I am doing a bunch of for loops and list operations ๐Ÿฅต

timid hamlet
#

hell naw that took me like 20 lines in java

#

huge chance I abused streams too much

fresh thunder
#

oh damn i shouldve taken the input as the provided file ๐Ÿ’€

timid hamlet
#

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

hard mason
#

calculates aoc answer in ~8^-8 days

hard mason
fresh thunder
#

you should implement weeks and months and years

timid hamlet
#

remove print for faster execution (real)

hard mason
#

I misspelled elves at the begging and I am too lazy to fix it, for the rest of AOC I will call them elfs

fresh thunder
#

๐Ÿ‘

timid hamlet
#

elevens

rugged wharf
#

a

gritty tiger
#

just remove any newlines

#

ez

prime jolt
#

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")

strong kiln
prime jolt
#

yeah haha

#

I did a similar thing for rust, but the result was longer

#

now to write a helper tool

woven isle
frail rivet
#

I find it extremely ugly

#

My opinion though. Others might like it.

wary bough
frail rivet
#

No

prime jolt
#

haha

frail rivet
#

I wish I kept discord open and didn't turn off my computer ๐Ÿ˜ญ

prime jolt
#

yay, got started on my helper

#

yoo it works

waxen mason
#

ooh

#

i'm gonna do something like that tonight actually

brittle jasper
plucky dune
#
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
brittle jasper
#

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()
violet hound
#

The thing I notice - why replace \n\n with break and then split on break?

prime jolt
#

instead of replacing with a break

prime jolt
#

I'd also give your variables more descriptive names

violet hound
#

You also only need to sort fl once

plucky dune
brittle jasper
prime jolt
brittle jasper
#

yeah, but you can transform the raw string in whatever way you need

prime jolt
#

mm, fair enough

#

what if I have decorators for both the solution and the input >.>

#

decorators all around

brittle jasper
#

i like the idea of :

@submit(year=2022, day=1, part=1)
def my_solution():
    ...
prime jolt
#

yeah, I had that kind of thing in mind for solutions too

brittle jasper
#

i mean the input handler could just be:

def input_handler():
    return do_something_with(raw_input(year=2022, day=1))
prime jolt
#

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

brittle jasper
#

might be too indirect

prime jolt
#
@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
brittle jasper
#

there's a lot of times where just keeping the raw input as something you can transform on one line will be easiest

prime jolt
#

yeah, I guess that's fair - it was a similar case with today

brittle jasper
#

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

waxen mason
#

my aoc helper last year had a testing feature where it tested it with example data

#

it worked most of the time

prime jolt
#

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 >.>

white terrace
#

./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?

fierce garnet
#

how are the scores calculated

white terrace
fierce garnet
#

definatly not gonna make it ๐Ÿ˜‚

white terrace
#

same bro

waxen mason
#

that

fierce garnet
#

someone posted a 1 liner GG

white terrace
#

does AoC get gradually harder or no

prime jolt
#

the later days are harder, yeah

fierce garnet
white terrace
#

shit

waxen mason
#

argument

fierce garnet
#

wait till u need 3hrs to get answer

prime jolt
#

stick with it! Challenges are nice :p

brittle jasper
white terrace
#

rust-analyzer doesn't workwith single file projects so 90% of my time was reading compiler errors

waxen mason
#

fair enough

fierce garnet
#

if u don't use some algorith that is

brittle jasper
#

which could be cool if it was general enough

#
transform(raw_input, np.array, (3, -1))
waxen mason
#

ooh

white terrace
#

cooool

waxen mason
#

i might try and give a go at a more general transform annotation for my helper

brittle jasper
#

but i usually do this with a combination of extract_ints, chunk and np.array

#

i think i could make it general

white terrace
#

what was yoursolution or algorithm for part 1?

prime jolt
#

(I do mean one generated by a cargo new, though)

white terrace
#

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()

white terrace
prime jolt
#

do that!

fierce garnet
#
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)```
#

๐Ÿ˜ญ

white terrace
fierce garnet
#

i kept getting weird answer

white terrace
#
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);
}
prime jolt
white terrace
#

i'll just keep running cargo check

#

i mean rustc

steep lynx
#

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

prime jolt
#

hello

white terrace
#

HAHAHAHAH

brittle jasper
#

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

white terrace
#

nim?

#

damn

brittle jasper
#

if you squint, it looks like compiled python

white terrace
#

meh

brittle jasper
#

you're meh

fierce jungle
brittle jasper
#

c

fierce jungle
#

good

brittle jasper
#

not much reason to compile to javascript unless you have some web application in mind or need js packages

fierce jungle
#

why would you ever

#

transpile to Objective-C

#

is there a reason

#

or C++

brittle jasper
#

probably compatibility reasons

fierce jungle
#

I suppose so

white terrace
#

i transpile

#

nim

#

into

#

php

brittle jasper
#

๐Ÿ˜ฏ

steep lynx
#

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)

brittle jasper
#

yep, python solutions are my primary ones

steep lynx
#

last year i gave up on the final problems

#

not this year ๐Ÿ˜ˆ

#

famous last words

brittle jasper
#

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)
steep lynx
#

aoc_lube lmfao

#

i need to start doing that as well

sudden dove
#

this was the most difficult so far ๐Ÿ˜”

clear river
#

So far

#

It was also the easiest so far

mighty birch
#
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

gritty tiger
#

nice

honest comet
#

Got Wrong answer for p1

#

ughh sorry

violet hound
#

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

frail rivet
#

Day 2?

violet hound
#

yeah my bad

#

day 2

woven isle
violet hound
#

oh shit my bad

woven isle
#

I wrote here about my day 2 solutions as well, but I since moved XD

violet hound
#

gone now. Yeah, it's really early morning for me lol

woven isle
#

Last year everything was in one channel, so it's kinda confusing

violet hound
#

9am being early XD

woven isle
#

I don't function properly at that hour

violet hound
fair kestrel
#

Anyway you can share everything?
From aoc_helper.fetch(1, 2022) to mapped to extract ints?

Thanks

tribal bear
#

(as well as a custom list)

fair kestrel
tribal bear
#

That's the one and yes there definitely is

#

from aoc_helper import list, extract_ints

fair kestrel
#

Thank you. I'll look at the source code to see everything it has

tribal bear
#

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

fair kestrel
#

Oh nice. Thanks for that info

toxic oar
#

:o what's so nice about the aoc_helper list?

reef stirrup
#
# 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()
violet hound
reef stirrup
#
# 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()
rare owl
#

AoC 2022 | Day 1 | Solutions & Spoilers

analog sentinel
#

What's iu.n_max?

modern apex
analog sentinel
#

doesn't just works with max?

#

Do you mean n as quantity?

modern apex
#

ye

analog sentinel
#

cool

woven isle
mossy tulipBOT
#

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]`.
modern apex
dapper gyro
#
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

sudden dove
#

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]))```
placid plinth
#

๐Ÿ˜Ž

median zinc
#

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:]))```
violet hound
median zinc
#

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

violet hound
median zinc
#

Thanks, hoping I donโ€™t have an RSI by the end of the month

lime valley
#
#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

violet hound
lime valley
# violet hound 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

violet hound
#

Hey, if your code works, thatโ€™s the most important thing!

lime valley
#

yeah true ๐Ÿ˜‚

violet hound
#

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

lime valley
#

like the names of the variable?

violet hound
#

If you split by \n\n first then you can split the input into their initial groups

lime valley
#

ohh yeah

violet hound
#

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

lime valley
#

yeah you know i actually did the try and except just for fun! thanks for the information anyway

prime jolt
#

@west blaze

#

can you see this?

frail rivet
#

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

frail rivet
#

i yield because return breaks my code for some reason

#

now it doesn't

prime jolt
#

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

west blaze
frail rivet
prime jolt
#
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
frail rivet
#

that's so good. that's jsut awesome

prime jolt
#

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

frail rivet
#

i have a question for part 2
do we have to calculate the whole thing?

#

ike the whole file

#

๐Ÿฅถ

prime jolt
#

yes

fallen dune
#
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
frail rivet
#

super idol

south rock
#

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?

fallen dune
#

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.

prime jolt
#

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:]

south rock
#

Ok, thank you for the feedback

#

Should probably brush up on some of the implicit syntax like "if not line"

dapper gyro
frigid yoke
violet hound
frail rivet
#

just create a gitignore and remove the input file too

frigid yoke
oak idol
#

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))
plucky thorn
#

wth 3 liners? i took like 200 lines ๐Ÿ˜ถ

frail rivet
#

ayy i got my first star :D