#AoC 2022 | Day 3 | Solutions & Spoilers

2375 messages · Page 3 of 3 (latest)

wanton arrow
#

if you find yourself struggling don't waste too much time on it, ask here, someone will tell you how to do the python part (while trying to avoid actual spoilers) some of the AOC puzzles will be harder, you want to spend more time on the puzzle and less on the basic stuff.
All in all, AOC should be fun and educational. I learn something new every year.

plush crater
#

will do in future the logic of them haven't been hard so far
just tryna get them done in cleanest way possible

#

without using 100 if and else statments

#

how do u read 3 lines at a time

wanton arrow
#

Also, read others answers and then consider rewriting some of your own if you see something you'd like to try.

#

you can zip it, or chunk it, or just use the index

plush crater
#

yeah i wanted to try this one but is this python?

wanton arrow
#

no, that's nim

#

different language

dark fjord
#

The question now is can github copilot see that you are making an AOC day and give the answer? hmmm.... there are a lot of answer on github in various languages.

plush crater
#

input might be different for different people

#

hence different answers

dark fjord
wanton arrow
plush crater
#
with open('zzzinp.text','r') as file:
    for i in range(3):
        lines_3 = [l for l in file][:3*i]
        print(lines_3)```
wanton arrow
plush crater
#

i was writing this but [0:3} never read first item

wanton arrow
plush crater
#

each time we call realine it reads a new line nice

#
with open('zzzinp.text','r') as file:
    lines = file.readlines()
    for i in range(0,len(lines), 3):
        lines_3 = [l for l in lines][i:3*(i+1)]
        clean(lines_3)  ```
#

i did this

wanton arrow
wanton arrow
#

Also, back to the first comment: You really want to avoid using global this way, in fact pretty much you never want to use the global keyword. It's almost always a bad practice, and mostly you only see it with new coders that are still figuring out how to use functions.

plush crater
#
letters = {v: k for k, v in enumerate(string.ascii_letters, 1)}

common_letters = []
total = 0


def clean(first_half):
    global common_letters
    a, b, c = first_half[0], first_half[1], first_half[2]
    common_letters.append(str(set(a).intersection(b).intersection(c)))


with open('zzzinp.text', 'r') as file:
    lines = file.read().splitlines()
    for i in range(0, len(lines), 3):
        lines_3 = [l for l in lines][i:3*(i+1)]
        clean(lines_3)


total = 0
for i in common_letters:
    total += letters[i.strip("'{}")]
print(total)```
wanton arrow
#

but if you're importing it, you'll want to put the inline code into a function so it doesn't get run when you import

plush crater
#

maybe that's y my bot was acting weird

#

how do u remember all the variables

#

put them into a dict?

wanton arrow
#

I don't remember any variables, I look up the ones I need when I need them.

#

like ascii_letters. If I couln't remember that, at least I know it exists and I can just check the string page on python docs.

#

then I import it from the string library.

radiant zealot
#
with open('day3\input.txt', 'r') as f:
    inputlist = f.read().split('\n')

total = 0
groupnum = 0

for num in range(int(len(inputlist) / 3)):
    position = -1
    group = [inputlist[groupnum], inputlist[groupnum + 1], inputlist[groupnum + 2]]
    for letter in group[0]:
        position += 1
        if letter in group[1] and letter in group[2] and letter not in group[0][:position]:
            if letter.lower() == letter:
                total += (ord(letter.lower()) - 96)
            else:
                total += (ord(letter.lower()) - 70)
    groupnum += 3

print(total)```

Pretty happy with my solution, if anyone has any tips please let me know!
plush crater
#

makes sense i'll try to avoide globals

wanton arrow
#
for letter in group[0]:
        position += 1
        if letter in group[1] and letter in group[2] and letter not in group[0][:position]:

vs:

unique = set(group[0]) & set(group[1]) & set(group[2])
radiant zealot
#

Wow, alright will do, anything else that sticks out?

wanton arrow
#

that seems pretty minor though, if you had of done it that way likely someone else would have said "put them in a list".

radiant zealot
#

oh yeah thats true, a list was not necessary

wanton arrow
mystic kindle
#

The reason that works is because of something called a set intersection - sets can only contain unique values, so no duplicates. Getting the intersection of two sets, A & B, gives you another set consisting of any values which are shared between the two sets.

radiant zealot
#

Damn these puzzles are really well thought out, making you use like every data type throughout the days if you want the most optimal solution

wanton arrow
#

instead of

groupnum = 0
for num in range(int(len(inputlist) / 3)):
    groupnum += 3

vs:

for groupnum in range(0, len(inputlist), 3):
wanton arrow
radiant zealot
#

Yeah ik but so far the most straightforward/optimal solutions have used lists, dictionaries and sets

radiant zealot
wanton arrow
#

yeah, we'll see a lot of those. expect queues and stacks to be relevant eventually. 🙂

radiant zealot
#

uh oh, I dont even know what they are xD

radiant zealot
wanton arrow
#

start defaults to 0, and step defaults to 1.

radiant zealot
#

np, yeah that makes sense that should be very helpful for later puzzles

wanton arrow
#

one of the things later puzzles will do is scale part 1 will have a naive solution that will not work for part 2, because part2 will be "now do part 1 another 2 billion times", so you'll need things like sets instead of lists to handle O(1) operations instead of O(n) and things like that

radiant zealot
#

Does the difficulty scale as we get closer to Christmas or is it random?

cursive sail
#

it's scales up

#

it hits the peak somewhere between 17-23, and then slows down near the end

#

weekends are also usually harder

plush crater
#

to make everyone feel good by EOY

radiant zealot
#

interesting

wanton arrow
#

If you hover over the dots you can see which dot was who and what time they had.

radiant zealot
#

I see, ty

wanton arrow
#

part of the problem is that the puzzle creators and testers think there are obvious answers that the public collectively misses, or vice versa the public find easier answers that the creator and testers missed. so the variance can sometimes be high.
this is compounded by them coming up with so many different input files. there was a path finding problem last year where 1 of the inputs part 2 could be solved like part 1 if you did part1 a certain way, but everyone else's part 2 was much more involved. So even within the puzzles there can be some variance.

jolly abyss
#

Im working on the basis of part two, and I feel like this should get every three keys into their own list, but for some reason i have this [...] item in my list, and I cant figure out anywhere on google if its actually there or what it means?

def part_two():
    with open("rucksacks.txt", "r") as f:
        data = f.read().split("\n")

    group = groups = []
    for d in data:
        if(((data.index(d) + 1) % 3) == 0):
            group.append(d)
            groups.append(group)
            group.clear()
        else:
            group.append(d)

['CjhshBJCSrTTsLwqwqwb', 'GtmnFHlDfcpHbLZjtTTRLWwb', 'fDfNHHjVFNvvrvVBJJdS', [...]]

#

I would rather not get the answer per se, but I have no idea why this is happening

unique pivot
#

I believe that third list is a really long list, but it's just denoted like that because it's too long

#

It's probaby because you're setting group and groups to the same list

jolly abyss
#

well i get a group of three elements in group add that to groups and then empty out group for the next three

unique pivot
#

!e

group = groups = []
group.append(1)
print(group)
print(groups)
broken condorBOT
#

@unique pivot :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | [1]
002 | [1]
jolly abyss
#

hmm

unique pivot
#

set them both on different lines

runic glacier
#

Can someone check over my find_common method? It's supposed to take a list of strings, and find out what letter is common between all of them:

    def find_common(self, *args: str) -> str:
        for i, text in enumerate(args):
            others = args[:i] + args[i+1:]
            for j in others:
                for letter in text:
                    if letter in j:
                        return letter
jolly abyss
#

this is weird

unique pivot
#

That would probably be because just appending group appends a reference to the list that group references. When you clear group, it clears all those lists because it's the same ist

jolly abyss
#

oh interesting

unique pivot
#

I'd suggest just slicing, then appending that

runic glacier
#

ah yikes

unique pivot
#

even with a common letter

runic glacier
#

that would explain why my guess is too low

mystic kindle
#

sets sets sets

runic glacier
#

i did use sets originally but i want to challenge myself

#

lol

unique pivot
#

yes, listen to aboo

mystic kindle
#

ah, lol

unique pivot
#

Looks like it returns as soon as it finds the first common letter between two of the strings

full bane
#

oh that's the point.

runic glacier
#

solved it

    def find_common(self, *args: str) -> str:
        for i, text in enumerate(args):
            others = args[:i] + args[i+1:]
            for letter in text:
                if all(letter in other for other in others):
                    return letter
#

repost if O(n^3)

jolly abyss
#

since i never reset it

runic glacier
#

now to see if i can optimize...

unique pivot
unique pivot
runic glacier
unique pivot
jolly abyss
runic glacier
#

it also contains the text i'm currently looping over

jolly abyss
#
def part_two():
    with open("rucksacks.txt", "r") as f:
        data = f.read().split("\n")

    group = []
    groups = []
    for d in data:
        if(((data.index(d) + 1) % 3) == 0):
            group.append(d)
            groups.append(group[-3:])
        else:
            group.append(d)
    print(groups)
#

first half of it

unique pivot
runic glacier
unique pivot
#

If the letter is common, then that means that any string that you iterate over will have that letter. So instead of iterating over everything, just iterate over the letters of the first one, and check if each letter of it is in the other strings.

runic glacier
#

It works BTW, same solution as before

full bane
#

i don't think it's cubic

jolly abyss
#

what are you trying to do?

cursive sail
#

or you could just use sets >.>

runic glacier
# full bane i don't think it's cubic
  • for letter in args[0]
  • all
  • letter in other for other in args
    unless i'm missing something else / misunderstanding time complexity for a certain thing
jolly abyss
#

yeah i used set intersection

unique pivot
jolly abyss
#

ah

cursive sail
#

boring

runic glacier
unique pivot
#

Robin have you solved it yet, or are you still working on it?

runic glacier
#

Solved both, thanks to y'all

jolly abyss
#

in part 2 we are not slicing the words like in part 1 right?

#

just comparing the entire words to each other?

runic glacier
#

actually the cool thing about find_common is that I used it in my part one as well

def part_one(self) -> str | int:
        total = 0
        for backpack in self.backpacks:
            c = len(backpack) // 2
            compartment_one = backpack[:c]
            compartment_two = backpack[c:]

            common = self.find_common(compartment_one, compartment_two)
            total += self.get_priority(common)
        return total
full bane
cursive sail
#

dang you actually used a class and everything

mystic kindle
#

fnacy

runic glacier
# cursive sail dang you actually used a class and everything

lol, part of my AoC helper. each day has a placeholder like

from aoc.solution import SolutionABC

class Solution2(SolutionABC):
    def __init__(self, content: str) -> None:
        ...

    def part_one(self) -> str | int:
        ...

    def part_two(self) -> str | int:
        ...
cursive sail
#

maintainable aoc? never heard of it.

plush crater
cursive sail
runic glacier
#

you go in and fill out whatever you want, and run a command

python -m aoc --day 2 --part 1
cursive sail
#

since they posted on twitter that they used it for day1

mystic kindle
#

all I did was hack together a wonky script for getting the boilerplate out of my way

#

otherwise its all salt's aoc_lube >.>

cursive sail
#

i just write the boilerplate at 11:55 🥴

unique pivot
runic glacier
#

I'm planning on adding more features like submission for CLI, and test cases

mystic kindle
#

well, I have to create a pdm project, add all my dependencies, the whole thing

runic glacier
plush crater
mystic kindle
#

hm, I could just have all the solutions be one pdm project and have them share dependencies because I don't care

unique pivot
mystic kindle
#

well, they all use the same dependencies anyways

cursive sail
#

the idea that ai can replace programmers is something i find absurd, at least right now

mystic kindle
runic glacier
cursive sail
#

but it is a great tool to augment the programming experience

runic glacier
#

gpt trippin

unique pivot
runic glacier
#

Hm might be worth keeping it in there then

#

Each project should be tied to a specific year

plush crater
plush crater
runic glacier
#

aint no way

cursive sail
#

it can solve simple aoc

runic glacier
#

gpt just did what i spent like 30 minutes doing

mystic kindle
#

it will probably have trouble once problems get harder

unique pivot
# runic glacier

I and someone else a while ago plugged in the AoC problems, it got pretty close

cursive sail
#

look at the last example

#

it should not give h, world does not include h

unique pivot
#

it created like 8 blank sets but yeah

plush crater
#

i don't think that matters as long as it understands what it needs to do

cursive sail
#

it has the right idea

runic glacier
cursive sail
#

but it cannot necessarily give correct code

mystic kindle
#

I copy+pasted day 3 into chatgpt, lets see what I get

runic glacier
#

our jobs are safe!

cursive sail
#

i am also incredibly sad that it does not know what rvsdg is

unique pivot
runic glacier
#

hahahha so something good did come out of it

unique pivot
cursive sail
mystic kindle
#

it gave me ```py
total_priority = 0

for rucksack in rucksacks:

Split the rucksack into two compartments.

first_compartment = rucksack[:len(rucksack) // 2]
second_compartment = rucksack[len(rucksack) // 2:]

Find the items that appear in both compartments.

common_items = set(first_compartment) & set(second_compartment)

Compute the sum of the priorities of the common items.

compartment_priority = sum(priority(item) for item in common_items)

Add the compartment priority to the total priority.

total_priority += compartment_priority

Print the total priority.

print(total_priority)

#

for part 1

runic glacier
#

moment

mystic kindle
#

where priority is ```py
def priority(item):
if item.islower():
return ord(item) - ord('a') + 1
else:
return ord(item) - ord('A') + 27

runic glacier
mystic kindle
#

lets see how it fares with part 2

#

I just did ```py
priorities = dict(zip(string.ascii_letters, range(1, 53)))

runic glacier
#

I was just going to do ord(item) - 64

vagrant acorn
#

I had copilot on for the first day and I did the first day a little late, and I didn't even write a comment and it auto completed the rest of the one liner for me

#

It was a little off, but close

cursive sail
mystic kindle
#

index is neater 👀

runic glacier
vagrant acorn
runic glacier
#

thats my solution

cursive sail
#

at it again with the functions

#

what is this nonsense about readable code

vagrant acorn
#

Well, I just made my own string

#

And did the index of that

runic glacier
cursive sail
#

it's not even golf

mystic kindle
#

it gave me ```py
def priority(item):
if item.islower():
return ord(item) - ord('a') + 1
else:
return ord(item) - ord('A') + 27

rucksacks = [
"vJrwpWtwJgWrhcsFMMfFFhFp",
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL",
"PmmdzqPrVvPwwTWBwg",
"wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn",
"ttgJtRGJQctTZtZT",
"CrZsJsPPZsGzwwsLwLmpwMDw"
]

total_priority = 0

Iterate through the rucksacks in groups of three.

for i in range(0, len(rucksacks), 3):
group = rucksacks[i:i+3]

Find the item types that appear in all three rucksacks.

common_items = set.intersection(*(set(rucksack) for rucksack in group))

Compute the sum of the priorities of the common items.

group_priority = sum(priority(item) for item in common_items)

Add the group priority to the total priority.

total_priority += group_priority

Print the total priority.

print(total_priority)

unique pivot
#

they've really already had their fun

runic glacier
#

mans trollin

cursive sail
#

@runic glacier these were my solutions

#

they weren't golf, just a lot messier

mystic kindle
#

I have ```py
priorities = dict(zip(string.ascii_letters, range(1, 53)))

def part_1(data: list[str]) -> int:
priorities_sum = sum(
priorities[(set(a) & set(b)).pop()] for a, b in [divide(2, i) for i in data]
)

return priorities_sum

def part_2(data: list[str]) -> int:
priorities_sum = sum(
priorities[(set(a) & set(b) & set(c)).pop()] for a, b, c in chunked(data, 3)
)

return priorities_sum
cursive sail
#

probably because i did them in like 8 minutes as fast as i could

runic glacier
#

maybe i should just stop trying

#

yeah the thing is i'm usually asleep when AoC drops

lyric folio
mystic kindle
runic glacier
#

so i just do em the next day at my own pace

#

i think it would be worse in rust

cursive sail
lyric folio
mystic kindle
#

method chaining is a required requirement for readability 😤

mystic kindle
#

I'm usually asleep, and when I wake up I need to go to school

runic glacier
#

skip school

#

give them a notice "im working on aoc fuck off nerds"

mystic kindle
#

or well, I am awake when AOC drops, but like, I'm busy procrastinating sleep

jolly abyss
#

welp, its probably excessively verbose but i finished my part 2

def part_two():
    with open("rucksacks.txt", "r") as f:
        data = f.read().split("\n")

    group = []
    groups = []
    for d in data:
        if(((data.index(d) + 1) % 3) == 0):
            group.append(d)
            groups.append(group[-3:])
        else:
            group.append(d)
    
    commons = []
    for group in groups:
        commons.append(list(set(group[0])&set(group[1])&set(group[2])))

    commons = [ord(char)-96 if char.islower() else ord(char)-38
               for common in commons for char in common]
    
    print(f"The sum of the common letters in each group of three is {sum(commons)}")
unique pivot
lyric folio
# runic glacier skip school

my gigachad mom genuinely suggested i should skip the first period class at uni if im that invested in aoc lmao

runic glacier
#

🤨

mystic kindle
#

"I'm sorry, but I won't be able to attend your educational establishment until the end of december due to important matters, the matter in question being an important and prestigious and importantly important programming advent calendar known as Advent of Code. Its important, BTW."

mystic kindle
#

"pls give me all As so I pass"

cursive sail
lyric folio
cursive sail
#

since it's an advent calendar

unique pivot
#

"care to explain this gap in your resume?"

runic glacier
#

lol i plan on putting all this on my github

mystic kindle
lyric folio
#

thanks

mystic kindle
hoary parcel
mystic kindle
#

"pls no fale"

runic glacier
#

now i just want to implement caching in my tool because






Oh, hello!  Funny seeing you here.

I appreciate your enthusiasm, but you aren't going to find much down here.
There certainly aren't clues to any of the puzzles.  The best surprises don't
even appear in the source until you unlock them for real.

Please be careful with automated requests; I'm not a massive company, and I can
only take so much traffic.  Please be considerate so that everyone gets to play.

If you're curious about how Advent of Code works, it's running on some custom
Perl code. Other than a few integrations (auth, analytics, social media), I
built the whole thing myself, including the design, animations, prose, and all
of the puzzles.

The puzzles are most of the work; preparing a new calendar and a new set of
puzzles each year takes all of my free time for 4-5 months. A lot of effort
went into building this thing - I hope you're enjoying playing it as much as I
enjoyed making it for you!

If you'd like to hang out, I'm @ericwastl on Twitter.

- Eric Wastl
cursive sail
#

4-5 months is a really long time, it's amazing how much work he puts into this

mystic kindle
#

he's absolutely based

runic glacier
#

he has to make the inputs in such a way that there's only 1 repeating character

cursive sail
#

i mean that part's obviously generation

#

he doesn't handwrite the inputs

runic glacier
#

true enough

mystic kindle
#

yeah, it'd be way too tedious to manually write them out

runic glacier
#

i thought he would given there's a few restrictions here

cursive sail
#

but writing the puzzles, and the input generation, and everything else is a lot

runic glacier
#

does he ever open source this stuff?

#

to get help

cursive sail
#

don't think so

hoary parcel
runic glacier
#

i mean i know you can probably just get the answers that way but for folks who don't mind being spoiled and want to help

cursive sail
#

there's a Credits section in the FAQ

#

and there's just a few beta testers

runic glacier
#

playing me huh

unique pivot
#

What does this guy doing for a living?

runic glacier
#

make advent of code puzzles probably

earnest sail
cursive sail
runic glacier
#

could probably fix that by slapping an appropriate license or something

#

i actually emailed the guy today

#

he got back to me really fast

unique pivot
lyric folio
runic glacier
#

my goofy ass after uploading my session token to github

lyric folio
#

bruh

#

lol

cursive sail
#

env vars my beloved

runic glacier
#

yeah i probably should've done that

#

but now it's stuck in the config.toml 🥴

hoary parcel
runic glacier
#

i'm guessing he's probably in that grace period when an AoC starts

#

it's still time consuming managing the ongoing one but I suppose maybe not as much as actually making them

#

regardless the guy is the most based gigachad i've ever seen

unique pivot
runic glacier
#

the thing is

cursive sail
#

that won't remove it from the history if someone has the hash

runic glacier
#

mine is set up as a "github template"

#

so when i make changes to the template repository i have to delete my actual 2022 aoc solutions

#

like delete the whole repo, make a new one, and clone it

unique pivot
#

oh you uploaded it to the template?

#

damn

runic glacier
#

yeah

raven kindle
#

Can someone help me understand why I can't append item to badge (at the very bottom)?

for sack in data:
    counter += 1
    commonItemTypes.append(sack)
    if counter == 3:
        counter = 0
        commonItemTypesOne, commonItemTypesTwo, commonItemTypesThree = commonItemTypes[0], commonItemTypes[1], commonItemTypes[2]
        commonItemTypes = []
        print(commonItemTypesOne, commonItemTypesTwo, commonItemTypesThree)
        for item in commonItemTypesOne:
            if item in commonItemTypesTwo and item in commonItemTypesThree:
                badge.append[item]
#

I defined badge as an empty list earlier

cursive sail
#

you need to use parentheses for append

#

it's a regular function

raven kindle
#

Ah, you're right

#

Sorry, that's a really silly mistake

#

Well, after that quick fix, here's my solution to day 3 part 2

with open('input.txt', 'r') as file:
    data = file.read().split()


def listToPriority(itemTypes):
    priorityList = []
    for letter in itemTypes:
        if letter.isupper():
            priorityList.append((ord(letter) - 38))
        else:
            priorityList.append((ord(letter) - 96))
    return sum(priorityList)


commonItemTypes = []
badge = []
counter = 0

for sack in data:
    counter += 1
    commonItemTypes.append(sack)
    if counter == 3:
        counter = 0
        commonItemTypesOne, commonItemTypesTwo, commonItemTypesThree = commonItemTypes[0], commonItemTypes[1], commonItemTypes[2]
        commonItemTypes = []
        for item in commonItemTypesOne:
            if item in commonItemTypesTwo and item in commonItemTypesThree:
                badge.append(item)
                break

badgeSum = listToPriority(badge)

print(badgeSum)
wanton arrow
cursive sail
#

which AI was that?

#

i had thought it was gpt-3

swift shuttle
#

Had to catch up for the last three days but I found a good use for that walrus operator in this one

from itertools import islice
from string import ascii_letters

import typer


# Answer 2545
def main(filename: typer.FileText = typer.Argument(...)):
    priority = 0
    while group := list(islice(filename, 3)):
        priority += (
            ascii_letters.index(
                list(
                    set(group[0].strip())
                    & set(group[1].strip())
                    & set(group[2].strip())
                )[0]
            )
            + 1
        )
    print(priority)


if __name__ == "__main__":
    typer.run(main)
quiet heath
#

This is the day 3 channel, please don’t post spoilers for day 4 in here

violet flicker
#

hello @radiant zealot, I've deleted your message

#

you could perhaps post your message in #1048826930759204864 and link it here (with a disclaimer) if you wish to do so

radiant zealot
#

Ah ok sorry about that

trail plover
mystic kindle
#

more specifically, doing a set intersection

unique heath
#

woohoo ⭐```py
ELF_CHUNKS = 3
LOWER_OFFSET = 96
UPPER_OFFSET = 38

def calculate_priority(item):
return ord(item) - (LOWER_OFFSET if item.islower() else UPPER_OFFSET)

with open("./input.txt") as file:
raw = file.read().splitlines()
input = [raw[i:i+ELF_CHUNKS] for i in range(0, len(raw), ELF_CHUNKS)]

priorities = []

for chunk in input:
unique_chunk = [set(rucksack) for rucksack in chunk]

for item in set("".join(chunk)):
    if all(item in rucksack for rucksack in unique_chunk):
        priorities.append(calculate_priority(item))

print(sum(priorities))

#

wait a minute 👀

#

i forgot about & lmfao

#

BRUHHHHHHHHHHHHHHHH

trail plover
dense birch
#
# aoc problem 3

lowercase_priorities = {chr(i + 0x60): i for i in range(1, 27)}
uppercase_priorities = {chr(i + 0x40): i + 26 for i in range(1, 27)}
priorities = lowercase_priorities | uppercase_priorities


def getinput():
    with open('3.txt') as f:
        return f.read().splitlines()


def splithalves(inpt):
    acc = []
    for line in inpt:
        hlen = len(line) // 2
        acc.append((line[:hlen], line[hlen:]))
    return acc


def dup_item_priority(lh, rh):
    dup_item ,= set(lh) & set(rh)
    return priorities[dup_item]


def groupthree(inpt):
    return [inpt[i:i+3] for i in range(0, len(inpt) // 3, 3)]


def common_item_priority(r0, r1, r2):
    common_item ,= set(r0) & set(r1) & set(r2)
    return priorities[common_item]


def main():
    inpt = getinput()
    print(sum(dup_item_priority(lh, rh) for lh, rh in splithalves(inpt))) # solution part 1
    print(sum(common_item_priority(r0, r1, r2) for r0, r1, r2 in groupthree(inpt))) # solution part 2


if __name__ == '__main__':
    main()
```why is my part 2 solution wrong?
dense birch
#

help pls

fallen sinew
dense birch
#

o thanks

nocturne umbra
#

what do you mean not all of them???

#
import string
with open("python_sandbox/RevivalOfCode/2022/Day3/data.txt", "r") as rucksack:
    rucksack = rucksack.read().split("\n")
    
sum = 0
  
alphabeth = {letter : ord(letter) - (96 if letter.islower() else 38) for letter in string.ascii_letters} #Makes a dictionary of the { keys(alphabeth):values(numbers) } for lower and uppercase letters
  
for compartments in rucksack:
    for j in compartments[0:int(len(compartments)/2)]: # FIRST COMPARTMENT (Gets first half of the string)
        for k in compartments[(int(len(compartments)/2))+1 :]: #SECOND COMPARTMENT (Gets last half of the string)
            if j in k:
                sum+= alphabeth[j]
print(sum)```
bruh... this doesnt work... idk why tho
#

says that my answer is too high

quiet heath
#

maybe that will help you figure out what's wrong

nocturne umbra
nocturne umbra
#

i tested it on the first 2 strings using for compartments in rucksack[:2]
which is
BzRmmzZHzVBzgVQmZLPtqqffPqWqJmPLlL
hpvvTDcrCjhpcrvcGGhfLHMlLtMCqflNlWPJlJ

quiet heath
#

you tested it on your actual input?

nocturne umbra
quiet heath
#

that's not what I'm referring to

#

there's an example input in the problem description itself

nocturne umbra
#

oh... i should try that

quiet heath
#

you have 6 example rucksacks and the priority numbers for each

#

they are literally given so that you can test your code against them :)

nocturne umbra
#

@quiet heath i figured out the problem...

quiet heath
#

Ah, what was it?

nocturne umbra
#

lets say the string is LLqwLL
youd want the value of L 38
what my programm was doing was getting the value for each identical letter in the halves
so id get 76

#

@quiet heath

quiet heath
#

Ah I saw that bug in someone else’s code before

#

aaaa being 2 instead of 1

nocturne umbra
#

yess

#

precisely

quiet heath
#

You should use sets

#

This issue won’t happen then

#

!d set

broken condorBOT
#
set

class set([iterable])``````py

class frozenset([iterable])```
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be [hashable](https://docs.python.org/3/glossary.html#term-hashable). To represent sets of sets, the inner sets must be [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset "frozenset") objects. If *iterable* is not specified, a new empty set is returned.

Sets can be created by several means:

• Use a comma-separated list of elements within braces: `{'jack', 'sjoerd'}`

• Use a set comprehension: `{c for c in 'abracadabra' if c not in 'abc'}`

• Use the type constructor: `set()`, `set('foobar')`, `set(['a', 'b', 'foo'])`...
nocturne umbra
#

ive never used sets before.. i just wirk on personal projects

quiet heath
#

They are part of the core Python language for a reason :)

nocturne umbra
nocturne umbra
quiet heath
#

Eh, I prefer to chat on the server if that’s ok

nocturne umbra
nocturne umbra
#

i did wha u told me and i still have issues

#
import string
with open("python_sandbox/RevivalOfCode/2022/Day3/data.txt", "r") as rucksack:
    rucksack = rucksack.read().split("\n")
    
sum = 0
  
alphabeth = {letter : ord(letter) - (96 if letter.islower() else 38) for letter in string.ascii_letters} #Makes a dictionary of the { keys(alphabeth):values(numbers) } for lower and uppercase letters
  
for compartments in rucksack:
    for j in set(compartments[:int(len(compartments)//2)]): # FIRST COMPARTMENT (Gets first half of the string)
        for k in set(compartments[int(len(compartments)//2)+1 :]): #SECOND COMPARTMENT (Gets last half of the string)
            if j in k:
                sum+= alphabeth[j]
print(sum)```
#

when i test the example the answer given is correct

but when i test the data they gave is it says that the number i got is too low.

alpine ferry
#
#Advent of code
#Problem 2
#--- Day 3: Rucksack Reorganization ---


import string 

with open("day3inp.txt") as f:
    inp = f.read()

li1 = [list(map(str, i.split("\n"))) for i in inp.strip().split("\n\n")]

alphabet_string = string.ascii_letters

#PART 1

letter_sum = 0
for i in li1[0]:
    half_length_item = len(i)//2
    first_half = i[:half_length_item]
    second_half = i[half_length_item:]
    common_item = ''.join(set(first_half).intersection(second_half))
    #find out the common letter between them
    letter_sum += (alphabet_string.index(common_item)+1)

print(letter_sum)


#PART 2

total_common_itemType_sum = 0
for i in range(len(li1[0])):
    if i%3==0:
        elf_group = li1[0][i:i+3]
        common_item_2 = ''.join(set(elf_group[0]).intersection(elf_group[1]))
        common_item_3 = ''.join(set(common_item_2).intersection(elf_group[2]))
        total_common_itemType_sum += (alphabet_string.index(common_item_3)+1)
    else:
        pass 

print(total_common_itemType_sum)
#

hehe 🙂

#

set 😎

#

i am happy that i got it on my first try and it also took so little time

broken condorBOT
dire garden
#

oh damn

#

what do you think about my way for p1?

# Rucksack Reorganization
# https://adventofcode.com/2022/day/3

import string


def calculate_item_priority(item: str):
    if len(item) != 1:
        raise ValueError("item must be a one-character-long string")
    if item not in string.ascii_letters:
        raise ValueError("item must be a letter")

    return string.ascii_letters.index(item) + 1


total_points = 0

input_ = open("Day 3/input.txt", "r")
for line, content in enumerate(input_, 1):
    content = content.removesuffix("\n")

    firstpart, secondpart = (
        content[: int(len(content) / 2)],
        content[int(len(content) / 2) :],
    )
    common_item = list(set(firstpart).intersection(set(secondpart)))[0]
    common_item_priority = calculate_item_priority(common_item)
    total_points += common_item_priority

print(total_points)