#AoC 2022 | Day 2 | Solutions & Spoilers
1447 messages Β· Page 2 of 2 (latest)
hmm ok
Can you explain this please?
well seems like i'm not the only one without a clue here
ValueError: too many values to unpack (expected 4)
doesn't work for me lol
.\d2cg.py < .\input2.txt
You didn't write it?
it relies on every line having 4 bytes
including the newline
I like that Part 2 is basically the opposite mapping
is rb read bytes? so its like... binary to start with which removes the use of ord?
when file name in the shortest code is changed to input.txt it's 88 bytes so still 18 bytes away
yes
for the stuff where i just exclude the part where the data is loaded into a variable i just replace it with ...for a,_,b in s.encode().split('\n')
what is ~
binary not
bitwise NOT operator
~x == -x - 1
ok fun, what's the j doing in there?
python complex number/imaginary number
yes
and also you can add them unlike ordinary tuples
christ
i have no idea how i still have a sane enough mind to explain since it's about to become midnight for me
Part 1: ```js
.split("\n").map(e=>({X:1,Y:2,Z:3})[e[2]]+{A:{X:3,Y:6,Z:0},B:{X:0,Y:3,Z:6},C:{X:6,Y:0,Z:3}}[e[0]][e[2]]).reduce((a,c)=>a+c)
Part 2: ```js
.split("\n").map(e=>({X:0,Y:3,Z:6})[e[2]]+{A:{X:3,Y:1,Z:2},B:{X:1,Y:2,Z:3},C:{X:2,Y:3,Z:1}}[e[0]][e[2]]).reduce((a,c)=>a+c)
js?
i get it mostly now, thx. the not operator is still confusing though
yes
especially with how it works with signed ints
let me make a Python solve
I used a class for today's challenge
just think of it as -x - 1
so like ```py
~2 == -3
~50 == -51
~(-50) == 49 # parentheses not needed
it might help to see what A, B, C and X, Y, Z gets converted to when read in bytes
is it 0, 1, 2?
>>> dict(zip(x:='ABCXYZ', map(ord, x)))
{'A': 65, 'B': 66, 'C': 67, 'X': 88, 'Y': 89, 'Z': 90}
the not operator is only confusing because python has dynamic sized ints
it is confusing
it's literally just -x - 1
What's confusing about "make all the 0's 1's and all the 1's 0's"
that's more confusing to beginners imo than just saying it's basically -x - 1
ok. so you aren't using ~ for anything special other than shorthand for subtraction and -1
it's a binary operator. They need to have an understanding of binary math to understand binary operators
oh i know what a not operator does to fixed size ints
well it's a unary operator π
but a bitwise unary operator
yes
It's just confusing with dynamic ints as you said.
that's often how it's used in code golfing
yeah
- is a binary operator because it operates on 2 values
~ is not, because it operates on one
how is it confusing?
like wrapping your head around the result or the implementation?
because I think of it as a bitwise operator
And a python integer starts with an infinite number of 0s
well yes
well no
Which it turns all into ones in theory
obviously not really
but it doesn't operate on the actual physical representation either
ok midnight hit and it sort of surprised me to suddenly see "3 December 2022" on my screen
so like thinking about the implementation?
well
thinking of what it's doing to the bits
>>> bin(5)
'0b101'
>>> bin(~5)
'-0b110'
the confusion is warranted, it can't be the actual complement (in something like C) since Python doesn't store numbers in a limited number of bits
Objects/longobject.c lines 4888 to 4893
if (IS_MEDIUM_VALUE(v))
return _PyLong_FromSTwoDigits(~medium_value(v));
x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_GetOne());
if (x == NULL)
return NULL;
_PyLong_Negate(&x);```
wots the -1 for?
subtract to cancel out the negative result from 1j*~
yeah, I mean it's a fake complement that doesn't actually do a bitwise complement (because Python numbers aren't even stored in two's complement anyways)
that's why Artemis was confused
i mean for small numbers that fit in a 30-bit integer it just does a normal bitwise not
yes, but that's not the confusing part
anyway do you like my Python solve
https://paste.pythondiscord.com/ifuqakerad.py
I didn't optimize for size, but I optimized for something else which I think people here might like
if you did bitwise not on an unsigned int in c or whatever you'd still have a position (or at least unsigned) number
bitwise not on a positive python int gives a negative int
damn
well because there are no unsigned number types in Python yea lol
exactly
what?
lmao
do you like it?
(except the internal C integers in a python integer)
it's horrific and full of underscores and dunders
nice
was it automated
i dont understand any of it. nice
yes, but it's the shortest possible one I think
could've probably used a walrus
where
everywhere
oh, you mean for the X, Y and Z variables?
I think this way is shorter, I'm not going for a one-liner but shortest file size in general
or actually, I guess it would be shorter with walrus yea since there's only one extra character, no new line and no need to specify the variable name for the first use (one char shorter)
what's the original code
import builtins
builtins.print(builtins.sum(builtins.map(lambda e:builtins.ord(e[2])-87+{'A':{'X':3,'Y':6,'Z':0},'B':{'X':0,'Y':3,'Z':6},'C':{'X':6,'Y':0,'Z':3}}[e[0]][e[2]],builtins.open(0,'r').read().split("\n"))))
can you tell I like underscores
I had fun with enums today. https://github.com/killjoy1221/aoc22/blob/main/day2.py
I don't bother with code quality π https://paste.pythondiscord.com/idavinereh
But got to use match-case in actual code!
My solution is hardcoded. I tried to be clever and decided I couldn't be bothered. Not gonna share because I'm so embarrassed.
Hello everyone!
Hey, if you solved it, that's what matters
It is not that bad to hardcode at times, in the plus side you were able to conquer the problem. 
@brave grail can we somehow use xors to shorten this further? π€
print(sum(b-87+(b+~a)%3*3-1j*~((~-a+b)%3+~-b%3*3)for a,_,b,_ in open(0,'rb')))
I too am having a
decided I couldn't be bothered.
thing with me rn
there is an todo in my day_2 π
https://github.com/Achxy/AoC-2022/blob/main/source/day_2.py
Advent of Code 2022 - https://adventofcode.com/2022 - AoC-2022/day_2.py at main Β· Achxy/AoC-2022
so I just also went for a less impressive solution in the end
I want to go for an impressive solution, just too tired to do it. Maybe I should allocate aoc-solving-time to the morning lol π₯΄
I coded it in the morning - still didn't help
if anything made it worse
I am not a morning person
just read the code above, yall have some seriously esoteric code
// Part2
var input2 = File.ReadAllLines("input.txt").Select(x => x.Split()).Select(y
=> (y[0] - 'A', y[1] - 'X'))
.Select(z => z.Item2 * 3 - 3 + ((z.Item2 - 2 + z.Item1 - 1) % 3 + 3) % 3 + 1)
.Sum();
``` did this one in c# the math took me like 2 hours to work out
yo whats :=
never seen it before
it's commonly called walrus operator
what does it do
further reading: https://realpython.com/python-walrus-operator/
bet
π
def solve():
lst = text.splitlines()
index = 0
score = 0
for i in lst:
index += 1
x = index % 3
p = {
'X':1,
'Y':2,
'Z':3
}
if True:
if x == 0:
score += 8+p[i[-1]]
elif x == 1:
score += 0+p[i[-1]]
else:
score += 3+p[i[-1]]
print(score)
print(len(lst))
solve()```what have i done wrong?
you seem to have ignored the game of rock paper scissors
that's an important part of the problem
I don't understand what you are doing with the index
basically mine 
wait i thought line 1 4 7 etc will always win and 2 5 8 lose and 3 6 9 draw
ok i misreaded
"""
Solution for
Day 1: Calorie Counting
"""
"""
rock: 1
paper: 2
scissors: 3
"""
player_choices = {
"A": 1,
"B": 2,
"C": 3,
"X": 1,
"Y": 2,
"Z": 3
}
with open("data.txt") as file:
data = file.readlines()
for idx,lines in enumerate(data):
data[idx] = lines.replace("\n","")
def part_one():
combinations = {
"A X": 3,
"A Y": 6,
"A Z": 0,
"B X": 0,
"B Y": 3,
"B Z": 6,
"C X": 6,
"C Y": 0,
"C Z": 3
}
total_score = 0
for lines in data:
score = combinations.get(lines) + player_choices.get(lines[2:])
total_score += score
print(total_score)
def part_two():
#dictionaity to store what points the player gets when he needs to win
win_table = {
"A": 2,
"B": 3,
"C": 1
}
loose_table = {
"A": 3,
"B": 1,
"C": 2
}
total_score = 0
for lines in data:
if lines[2:] == "X":#lose
total_score += loose_table.get(lines[:1])
elif lines[2:] == "Y":#draw
total_score += 3 + player_choices.get(lines[:1])# 3 points for draw + amount of points for the character the opoonent has
elif lines[2:] == "Z":#win
total_score += 6 + win_table.get(lines[:1])# 6 points for winning + amount of points given for winning symbol -> use combinations dictionairy
print(total_score)
part_two()
noob solution ;-;
Ugh, spent way too long before I realised the "bonus" was 1-indexed (1 extra for rock instead of 0)
from aocd import submit, lines
score = 0
decoded = {c: (i % 3) for (i, c) in enumerate("ABCXYZ")}
bonus = {c: i + 1 for (i, c) in enumerate("XYZ")}
score_table = {
f"{them} {us}": ((decoded[us] - decoded[them] + 1) % 3) * 3 + bonus[us]
for them in "ABC"
for us in "XYZ"
}
result = sum(score_table[l] for l in lines)
submit(result, part="a")
move_table = {
f"{them} {outcome}": decoded[outcome] * 3
+ (decoded[outcome] + decoded[them] - 1) % 3
+ 1
for outcome in "XYZ"
for them in "ABC"
}
print(move_table)
assert move_table["A Y"] == 4
assert move_table["B X"] == 1
assert move_table["C Z"] == 7
result = sum(move_table[l] for l in lines)
submit(result, part="b")
me trying to use lambda in 1 line to solve whole problem: π€
# part 1
with open("input.txt") as file:print(sum(1+(B:=ord(b)-ord("X"))+3*((B-ord(a)+ord('A'))%3+1)for a,_,b_ in file))
# part 2
with open("input.txt") as file:print(sum(3*(B:=ord(b)-ord("X"))+((ord(a)-ord('A')-1+B)%3+1)for a,_,b,_ in file))
```Can be less verbose but I left some of the math and ords uncancelled
https://paste.pythondiscord.com/edogerelih this simple
def d2p2(text):
lst = text.splitlines()
dic = {
'A':1,
'B':2,
'C':3
}
func = lambda item:dic[item[0]] if item[-1] == 'X' else dic[item[0]]+3 if item[-1] == 'Y' else dic[item[0]] +6
for i in lst:
yield func(i)```ok why is this not working
If I chose paper and you're supposed to lose, you can't choose paper
pandas still rocks
# Part 1
m = pd.Index([*"ABCXYZ"]).to_series().pipe(lambda s: s.groupby(s).ngroup().mod(3).add(1))
print(pd.read_csv("day_2.input", sep=" ", header=None).apply(lambda c: c.map(m)).assign(d=lambda fr: fr.diff(axis=1)[1]).pipe(lambda fr: fr[1].add(fr.d.mod(3).add(1).mul(3).mod(9))).sum())
# Part 2
w = m[[*"XYZ"]].reset_index().pipe(lambda fr: fr.set_axis(fr[0]).drop(columns=0).squeeze())
print(pd.read_csv("day_2.input", sep=" ", header=None).assign(**{"1": lambda fr: fr.apply(lambda c: c.map(m)).sum(1).sub(2).mod(3).pipe(lambda s: s.add(s.eq(0).mul(3))).map(w)}).drop(columns=1).rename(columns=int).apply(lambda c: c.map(m)).assign(d=lambda fr: fr.diff(axis=1)[1]).pipe(lambda fr: fr[1].add(fr.d.mod(3).add(1).mul(3).mod(9))).sum())
method chaining for the win
that is an impressive number of lambda functions!
wow π΅
https://paste.pythondiscord.com/okoxapevil code for both of the solves
basically this π€£
I personally prefer numpy
import numpy as np
a = np.genfromtxt("input2", dtype = 'c').view(np.uint8).astype(int)
part_1 = 3*np.sum(((b := (a[:,1] - 23 - a[:,0])%3))%2-b//2)+3*a.shape[0] + np.sum(a[:,1] - 87)
part_2 = np.sum((a[:,0] + a[:,1]-154)%3 + 1) + 3*np.sum(a[:,1]-89) + 3*a.shape[0]
what does ```py
a[:,1]-23-a[:,0]
A is 65 is ascii, while X is 88
The difference between your move and your opponents move is (you-opponent)%3
that is a[:,1]-23-a[:,0]) % 3
kill me i dont understand it π«
bump, is it a good approach?
You mean the indexing or the magical -23?
the indexing
im too dumb to understand numpy π
Numpy multi-dimensional indexing
me goes offline and sleep because dont understand what is numpy multi-dimension indexing
its like list indexing but multiple
list[1:2]
matrix[1:2, 2:3]
Do you have the full code?
how can i do syntax highlighting?
!code read the embed
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Ctrl+shift+c usually copies from terminal
You missed the py on the opening of backticks for the colours π
You're iterating over the file twice. Files get "used up", after the first loop there's nothing there.
Put file.seek(0) before the second loop to rewind your file to the beginning
like this? ```py
for lines in file.seek(0):
No. Just file.seek(0) before the loop. The loop should be still the same as it was
Btw, do young people nowadays even know what "rewind" means? I mostly associate it with cassettes, so I'm curious how younger people think about this word
yeah, i think its common on youtube and other video players
My answer is too high [15802]
should i remove the second for loop
Before I had only one for loop that all added to sum
however, only 'A' , 'B' , 'C' values actually added to sum
Here is my original attempt my result is 4681 which is too low
Also, a/b/c mens what elves showed. Your own score is dependent on x/y/z
why does scores exist?
if there's no nested loops, you can just return sum at the end
i just never refactored, i can take it out
oh did you read the question as there being multiple tournaments of RPS?
i thought there might be initially but yeah no in the end
Where you have A X, change elif to just if - that way those double letter conditions will be checked regardless of one-letter conditions
rock, paper, scissor, and cheat - 2star baby
pro tip just do Z every time
rust match function
You got the order wrong.
B X means paper vs rock means L. B Z is W
C X is W, C Y is L
yeah i just tried that and it didnt work maybe i missed something
omg
A Y
B X
C Z
This example was supposed to give 15
I get 9
Did you fix what I said?
believe so let me scan through
You still didn't fix what I said
A Y is a W, even the example says so
You got the order wrong.
B X means paper vs rock means L. B Z is W
C X is W, C Y is L
that looks a touch esoteric!
it worked thanks, I just needed to redo all the conditions since I thought A B C was your own data
test it plz
man, that's really close to my solution
haha me who used a giant if statement
ok, I stole code with the lookup values just to test <4s. of which just reading the 4GB file is the majority
(I'll now go back to not bother about optimization on a trivial problem)
Prompt?
I guess that's AoC 2023 leaderboard that will be entirely untrustworthy.
We will be, we are competing with bots . Good or bad?
I guess like chess or similar...
Very verbose (part two was way less clean than I want, but it works): https://www.damoncroberts.com/sections/blog/posts/advent_of_code/advent_of_code.html
I would not classify myself as a wonderful coder, but Iβll give it a go. 2021 was attrocious and I did not really come up with a single document to show my answers. But hereβs post-2022 attempts!
def part_one():
puzzle_input = utils.get_puzzle_input(day="two")
rpc_scores = {"X": 1, "Y": 2, "Z": 3}
wins = ["A Y", "B Z", "C X"]
losses = ["A Z", "B X", "C Y"]
ties = ["A X", "B Y", "C Z"]
score = 0
for round_ in puzzle_input.splitlines():
score += rpc_scores[round_.split()[-1]]
if round_ in wins:
score += 6
elif round_ in losses:
continue
elif round_ in ties:
score += 3
return score
def part_two():
puzzle_input = utils.get_puzzle_input(day="two")
rpc_scores = {"A": 1, "B": 2, "C": 3}
outcome_scores = {"X": 0, "Y": 3, "Z": 6}
# Position 0 gives what you need to win
# Position 1 gives what you need to lose
shape_map = {"A": ["B", "C"], "B": ["C", "A"], "C": ["A", "B"]}
score = 0
for round_ in puzzle_input.splitlines():
shape, outcome = round_.split()
score += outcome_scores[outcome]
if outcome == "X":
score += rpc_scores[shape_map[shape][1]]
elif outcome == "Y":
score += rpc_scores[shape]
elif outcome == "Z":
score += rpc_scores[shape_map[shape][0]]
return score
Here are my solutions π
Probably not the most elegant
But hey I mean they both worked first try at least
#d2 p1
def d2p1(text):
lst = text.splitlines()
func = lambda item:7 if item[0] == 'C' and item[-1] == 'X' else 8 if item[0] == 'A' and item[-1] == 'Y' else 9 if item[0] == 'B' and item[-1] == 'Z' else 1 if item[0] == 'B' and item[-1] == 'X' else 2 if item[0] == 'C' and item[-1] == 'Y' else 3 if item[0] == 'A' and item[-1] == 'Z' else 4 if item[0] == 'A' and item[-1] == 'X' else 5 if item[0] == 'B' and item[-1] == 'Y' else 6
for i in lst:
yield func(i)
#d2 p2
def d2p2(text):
lst = text.splitlines()
func = lambda item:1 if item[-1] == 'X' and item[0] == 'B' else 2 if item[-1] == 'X' and item[0] == 'C' else 3 if item[-1] == 'X' and item[0] == 'A' else 4 if item[-1] == 'Y' and item[0] == 'A' else 5 if item[-1] == 'Y' and item[0] == 'B' else 6 if item[-1] == 'Y' and item[0] == 'C' else 7 if item[-1] == 'Z' and item[0] == 'C' else 8 if item[-1] == 'Z' and item[0] == 'A' else 9
for i in lst:
yield func(i)```this is mine lol
wow
oh my
aoc is turning into #esoteric-python
π
def d2p1(text):
return map(lambda item:7 if item[0] == 'C' and item[-1] == 'X' else 8 if item[0] == 'A' and item[-1] == 'Y' else 9 if item[0] == 'B' and item[-1] == 'Z' else 1 if item[0] == 'B' and item[-1] == 'X' else 2 if item[0] == 'C' and item[-1] == 'Y' else 3 if item[0] == 'A' and item[-1] == 'Z' else 4 if item[0] == 'A' and item[-1] == 'X' else 5 if item[0] == 'B' and item[-1] == 'Y' else 6, text.splitlines())
the absurd amount of if[-elif]-else required in most solutions posted here makes me question the difficulty of this day
it's a remarkably simple problem
just fairly repetitive (at least with the naΓ―ve soluion? i've seen some clever ones)
yep
why not return the sum? or better just return the value, and map the function ?
IMO the naive solution is the best solution to this problem, as it is readable (with normal formatting).
but more fun to do a clever solution
print(sum("B XC YA ZA XB YC ZC XA YB Z".index(line.strip())//3+1 for line in open('input.txt')))```
@brave grail I tried to limit the amount of ifs and elses in mine
.
impressive
My actual solution: https://github.com/killjoy1221/aoc22/blob/main/day2.py#L92-L101
day2.py lines 92 to 101
def part1(data: MoveData):
move_map = {"X": "A", "Y": "B", "Z": "C"}
def map_data(line: tuple[ABC, XYZ]):
a, b = line
return Move(a), Move(move_map[b])
game = Game()
game.play(map(map_data, data))
return game.score```
nice.
looks pretty clean :)
now that's closer to what I did. you can probably clean it up by removing the spaces.
data = f.read().replace(' ','').splitlines()
sum(map(' BXCYAZAXBYCZCXAYBZ'.index,data))//2
I did enjoy this meme from the subreddit
https://i.redd.it/gol8dkkucf3a1.jpg
same
i still have no idea how i managed to formulate it
arrange your enum in such a way that you can do it all based on the ordinal
it's a single expression
Oh, that looks nice. I think I'll revise mine. 
the next enum will always beat the previous one. The first enum will beat the last. Vice versa for losing
i remember being so worried about finding the answer much faster
like wtf did i do here
For p1 I made a list of pairs of enum members, and then assigned win or lose based on looking up a pair in the list and the order of the members within the pair
okay, revised. py print(*(sum(part.index(a+b)//2+1 for a,b in zip(*2*[iter(open('input.txt').read().split())])) for part in ["BXCYAZAXBYCZCXAYBZ", "BXCXAXAYBYCYCZAZBZ"]))
i think you were right. it looks cleaner without spaces. βΊοΈ
My smol brain solutions, at least they're one line
def day_2():
def part_one():
return sum([((a:={"A":1,"B":2,"C":3}[o])+(b:={"X":1,"Y":2,"Z":3}[u]))*0+(3if a==b else 6if a-b in(-1,2)else 0)+b for o,u in[c.split()for c in DATA.splitlines()]])
def part_two():
return sum([((a:={"A":1,"B":2,"C":3}[x])+(b:={"X":0,"Y":3,"Z":6}[y]))*0+((a if b==3else 1if b+a in(2,9)else 2if b+a in(3,7)else 3)+b)for x,y in[c.split()for c in DATA.splitlines()]])
return part_two()
Essentially I turned the inputs into numbers (1, 2, 3 for rock, paper, scissors and the point values for the needed answer), then I wrote out all the comparisons. I noticed some patterns when performing math on the two values being compared, so I grouped the resulting values based on an operation that yielded unique results for each possible outputted value. Then I just summed that list and made it one line
what in the world ?! that's insane how did you figure that out?
It's interesting to see all the different ways people solve the same problem
agreed, I kind of like the whole using ord, I don't know why it really appealed to me at the time mind you, it's not the most legible code...
I did tdd so you can see my tests along with the code in a sub directory, but I'm still trying to think how I can clean it up a little bit...
figure what out? i mean the zipping part is pretty self-explanatory. and then i only had to sort the possible inputs by score value. 
I considered that, I just used dictionaries tho
did someone say "not the most legible code"?
lol i like how you give a spaghetti code warning
It's not like the other one is any more readable either
I'm no better my code isn't any more readable
I feel like that's one of those please increment comments thats all π
self: int π₯΄
no. it's fine.
One thing I like about AoC is that no matter how good your code is or how clever your methods are, you get the exact same answer as everyone else
cough lanternfish cough
totally agree
sometimes code only works for your input.
that would suck
Well the 2.5k lines of input greatly reduces the likelihood of that happening
yes. usually when code works it works. but sometimes the input doesn't contain all border cases.
I had someone at work trying to solve the day in excel so I wouldn't put it pass someone to brute force the answer
day 1 in excel, they eventually gave up
yup, another person figured out how to do it in vbscript, I was impressed
I coded in VBA for 3 years, then SAS and now I mostly do Python
I'm really glad for the change because I couldn't imagine doing AOC in VBA...
I guess you could potentially do it in sql but that could would be terrible
sql select column1, column2, partition blah blah blah
wouldn't recommend it
figuring out how to do advent of code using minecraft command blocks
Theoretically it's Turing complete, so it could be done. I made an addition calculator w/ redstone once, maybe there's some way to turn this problem into some binary operations
Ofc getting the input would take a while lol
I meant what prompt did you use,? π
copied and pasted the problems from AoC
and below i wrote something like βwrite code to solve this problemβ
print(sum([1 if p[1] == 'X' and p[0] == 'B' else 2 if p[1] == 'X' and p[0] == 'C' else 3 if p[1] == 'X' and p[0] == 'A' else 4 if p[1] == 'Y' and p[0] == 'A' else 5 if p[1] == 'Y' and p[0] == 'B' else 6 if p[1] == 'Y' and p[0] == 'C' else 7 if p[1] == 'Z' and p[0] == 'C' else 8 if p[1] == 'Z' and p[0] == 'A' else 9 for p in [line.split() for line in open('pin.txt', 'r').readlines()]]))
is this solution acceptable
Yeah
And the way it explains it
Exactly like a real human
Why isnβt my code working?
Broken
i think your win_list is actually your lose_list.
AZ, BX, CY are the combinations where you lose the game.
score=sum((a+1+b)%3+1+b*3+3 for a,b in map(lambda str: ((-1 if str[0]=="A" else 0 if str[0]=="B" else 1, -1 if str[2]=="X" else 0 if str[2]=="Y" else 1)), string.split("\n"))) One line solution for part 2
string is the input
The worst part is mapping the letters into numbers
how do you guys even do 1 liners... I mean I am no programmer but jesus it seems like something that can damage my brain haha
just some if else statements
Any way I can improve this?
class OpponentResponse(Enum):
A = "ROCK"
B = "PAPER"
C = "SCISSORS"
class MyResponse(Enum):
X = "ROCK"
Y = "PAPER"
Z = "SCISSORS"
class Scores(Enum):
ROCK = 1
PAPER = 2
SCISSORS = 3
class Outcome(Enum):
LOSE = 0
DRAW = 3
WIN = 6
WIN_CONDITIONS: dict[tuple[OpponentResponse, MyResponse], int] = {
(OpponentResponse.A, MyResponse.X): Outcome.DRAW.value,
(OpponentResponse.B, MyResponse.Y): Outcome.DRAW.value,
(OpponentResponse.C, MyResponse.Z): Outcome.DRAW.value,
(OpponentResponse.A, MyResponse.Z): Outcome.LOSE.value,
(OpponentResponse.C, MyResponse.Y): Outcome.LOSE.value,
(OpponentResponse.B, MyResponse.X): Outcome.LOSE.value,
(OpponentResponse.C, MyResponse.X): Outcome.WIN.value,
(OpponentResponse.B, MyResponse.Z): Outcome.WIN.value,
(OpponentResponse.A, MyResponse.Y): Outcome.WIN.value,
}
def calculate_total_score(input: str) -> int | str:
"""
Calculates the total score from playing a rock, paper, scissors game
according to a given input
"""
total = 0
path = Path(input)
if path.exists():
with path.open(mode="r") as file:
for line in file:
line = line.split()
my_response = str(MyResponse[line[1]].value)
total += Scores[my_response].value
total += WIN_CONDITIONS[(OpponentResponse[line[0]], MyResponse[line[1]])]
return total
return "File does not exist"
print(calculate_total_score("input.txt"))
Not sure the first two enums are good usage of enums
Second two are more what Iβd expect
What would you substitute then?
Tbh dictionaries. Map a string to one of the other two enum members
Ok yea that would work also. Thanks
I did a few of the days last year in Excel
what are these long strings?
score = 0
for x,y in zip(*2*[iter(open('i').read().split())]):
score += [0,6,3,0][ord(x)-ord(y)+21] + ord(y) - 87
print(score)
Any ideas why this is wrong?
I got 11325 as my output
The inputs are all different
I'm not sure, sorry
let me try and debug and see
this part 1 or 2?
one
i can never quite tell with the golfed solutions
thats the point ;p
hmm, i tried this now
score = 0
for x,y in zip(*2*[iter(open('i').read().split())]):
score += [0,0,6,3,0,6][ord(x)-ord(y)+25] + ord(y) - 87
print(score)
does it work?
nope
lol
doing so now
so it doesn't work on the test input either
but I'm running the test input a row at a time
A Y should be 8, but I get 2
oh wait you edited it again
nope still wrong, still get 2
Final solution π€·ββοΈ https://github.com/DJJ05/AOC2022/blob/main/2/main.py
Aim was unreadability
Although pinned soln bests me
ah fuck, I forgot to push mine to github
I got to use match for something, at least
I like making oneliners just for the fun
Its formatted onto multiple but the spirits there
I feel like my answer for day 2 is very... organic
Letβs see?
def parse_round(moves):
#X -> rock, Y-> Paper, Z-> scissors
move_score = {'X':1, 'Y':2, 'Z':3, }
vict_score = {'L':0, 'T':3, 'W':6, }
opp_map = {'A':'X', 'B':'Y', 'C':'Z'}
results = ["T", "W", "L"]
opp = opp_map[moves[0]]
mine = moves[1]
# if opp==mine:
# result= "T"
score_delta = move_score[mine]-move_score[opp]
result = results[
( score_delta )%3
]
print(mine, opp, score_delta, result)
return move_score[mine]+vict_score[result]
if __name__ == '__main__':
total_score = 0
with open('input.txt', 'r') as rounds:
for line in rounds:
moves = line.rstrip().split(' ')
total_score+= parse_round(moves)
print(total_score)
part A
move_score = {'X':1, 'Y':2, 'Z':3, }
vict_score = {'L':0, 'T':3, 'W':6, }
opp_map = {'A':'X', 'B':'Y', 'C':'Z'}
results = ["T", "W", "L"]
def parse_round(moves):
#X -> rock, Y-> Paper, Z-> scissors
opp = opp_map[moves[0]]
mine = moves[1]
# if opp==mine:
# result= "T"
score_delta = move_score[mine]-move_score[opp]
result = results[
( score_delta )%3
]
print(mine, opp, score_delta, result)
return move_score[mine]+vict_score[result]
def solve_round(round_data):
victory = {'A':'Y', 'B':'Z', 'C':'X'}
loss = {'A':'Z', 'B':'X', 'C':'Y'}
opp = round_data[0]
result = round_data[1] #X-> lose Y->draw z->win
# opp = opp_map[round_data[0]]
result_number = {"X":2, "Y":0, "Z":1}
if result == 'Y':
choice = opp_map[opp]
if result == 'Z':
choice = victory[opp]
if result == 'X':
choice = loss[opp]
return [opp, choice]
if __name__ == '__main__':
total_score = 0
with open('input.txt', 'r') as rounds:
for line in rounds:
round_data = line.rstrip().split(' ')
moves = solve_round(round_data)
total_score+= parse_round(moves)
print(total_score)
part B
I at least was able to reuse the parse round function, so that's not too bad, but I gave up on being clever to reverse the round
I shouldn't be too hard on myself because it was started on a wrong assumption about what the input data meant, so of course the abstractions are bad
Honestly you weren't far off a really small solution.
If you kept going with the dicts this would decrease your code by like 90%
I only started today, so I got an answer and moved on, I'll try editing day 1 and 2 tomorrow and like
with open('input.txt', 'r') as file:
data = file.read().split()
shapeScore = {'A': 1, 'B': 2, 'C': 3}
loseScore = {1: 3, 2: 1, 3: 2}
winScore = {1: 2, 2: 3, 3: 1}
opponentMove = ['A', 'B', 'C']
response = ['X', 'Y', 'Z']
opponentMoves = []
responses = []
score = 0
for letter in data:
if opponentMove.count(letter) > 0:
opponentMoves.append(letter)
else:
responses.append(letter)
for letter in responses:
if letter == 'Z':
score += 6
elif letter == 'Y':
score += 3
else:
continue
for i in range(len(opponentMoves)):
if responses[i] == 'Y':
score += shapeScore[opponentMoves[i]]
elif responses[i] == 'X':
score += loseScore[shapeScore[opponentMoves[i]]]
else:
score += winScore[shapeScore[opponentMoves[i]]]
print(score)
My solution for part 2
Not super elegant but I'm fairly proud of it
# aoc problem 2 part 1
win_scores = {
'A': {'Y': 6, 'Z': 0, 'X': 3},
'B': {'Z': 6, 'X': 0, 'Y': 3},
'C': {'X': 6, 'Y': 0, 'Z': 3}
}
shape_scores = {'X': 1, 'Y': 2, 'Z': 3}
def process_input():
with open('2.txt') as f:
return [l.split(' ') for l in f.read().splitlines()]
def score(opponent, player):
return win_scores[opponent][player] + shape_scores[player]
def main():
print(sum(score(o, p) for o, p in process_input()))
if __name__ == '__main__':
main()
# aoc problem 2 part 2
win_scores = {'X': 0, 'Y': 3, 'Z': 6}
shape_scores = {
'A': {'X': 3, 'Y': 1, 'Z': 2},
'B': {'X': 1, 'Y': 2, 'Z': 3},
'C': {'X': 2, 'Y': 3, 'Z': 1}
}
def process_input():
with open('2.txt') as f:
return [l.split(' ') for l in f.read().splitlines()]
def score(opponent, player):
return win_scores[player] + shape_scores[opponent][player]
def main():
print(sum(score(o, p) for o, p in process_input()))
if __name__ == '__main__':
main()
The long strings are the possible combinations of A,B,C and X,Y,Z sorted by their score value.
"BXCYAZAXBYCZCXAYBZ" for part 1, and "BXCXAXAYBYCYCZAZBZ" for part 2.
In part 1 BX has score 1, CY has score 2, AZ has score 3, etc.
In part 2 BX has score 1, CX has score 2, AX has score 3, etc.
only just got round to reading all this (again, tysm for the breakdown) and I just wanna say that this is absolutely genius, took me a second to get it, but wow.
No issues, glad you found it helpful
I like how everyone here kinda made their solution simple. Would my OOP approach be an overkill? https://github.com/Qoyyuum/adventofcode/tree/main/2022/day02
Not an overkill at all, and you arenβt the only one with an overkill solution :)
131 lines π
def d2p1(text):
lst = text.splitlines()
func = lambda item:7 if item[0] == 'C' and item[-1] == 'X' else 8 if item[0] == 'A' and item[-1] == 'Y' else 9 if item[0] == 'B' and item[-1] == 'Z' else 1 if item[0] == 'B' and item[-1] == 'X' else 2 if item[0] == 'C' and item[-1] == 'Y' else 3 if item[0] == 'A' and item[-1] == 'Z' else 4 if item[0] == 'A' and item[-1] == 'X' else 5 if item[0] == 'B' and item[-1] == 'Y' else 6
for i in lst:
yield func(i)
def d2p2(text):
lst = text.splitlines()
func = lambda item:1 if item[-1] == 'X' and item[0] == 'B' else 2 if item[-1] == 'X' and item[0] == 'C' else 3 if item[-1] == 'X' and item[0] == 'A' else 4 if item[-1] == 'Y' and item[0] == 'A' else 5 if item[-1] == 'Y' and item[0] == 'B' else 6 if item[-1] == 'Y' and item[0] == 'C' else 7 if item[-1] == 'Z' and item[0] == 'C' else 8 if item[-1] == 'Z' and item[0] == 'A' else 9
for i in lst:
yield func(i)
```mine
10 lines
π
:O no way lmao, i came here to post my overengineered solution as well
https://paste.pythondiscord.com/yowurepuso.py
so behind on aoc π but had an amazing camp this weekend, so works lol
I like how you use Enums on this one. Really nice π
I also used enums
#Advent of code day 2
#Problem 2
#--- Day 2: Rock Paper Scissors ---
with open("day2inp.txt") as f:
inp = f.read()
li1 = [list(map(str, i.split("\n"))) for i in inp.strip().split("\n\n")]
opponent_li = ['A','B','C']
my_li = ['X','Y','Z']
#Rock beats Scissors... X beats C... A beats Z... 1-3
#Paper beats Rock... Y beats A... B beats X...2-1
#Scissors beats Paper... Z beats B... C beats Y...3-2
#PART 1
score = 0
for i in li1[0]:
first_card = opponent_li.index(i[0])
last_card = my_li.index(i[2])
if first_card == last_card:
score += (last_card+1) + 3
elif (i == 'C X') or (i == 'A Y') or (i=='B Z'):
score += (last_card+1) + 6
else:
score += (last_card+1) + 0
print(score)
#PART 2
win_li = ['C','A','B']
lose_li = ['B','C','A']
score2 = 0
for i in li1[0]:
if i[2] == 'X':
score2 += (lose_li.index(i[0])+1) + 0
elif i[2] == 'Z':
score2 += (win_li.index(i[0])+1) + 6
else:
score2 += (opponent_li.index(i[0])+1) + 3
print(score2)
not really satisfied with my code
but hey it works π
thought about using dictionary which would make the code shorter
but too lazy to pull that off
it's medium in size though looks big because of comments
no way you hardcoded all that π
lol
with open('DAY_2/input.txt') as f:
data = f.read().splitlines()
VALUES = {'X': 1, 'Y': 2, 'Z': 3}
PLAYER_OPPONENT = {'X': 'A', 'Y': 'B', 'Z': 'C'}
def rps(data):
data.split()
OPPONENT = data[0]
PLAYER = data[2]
if OPPONENT == PLAYER_OPPONENT[PLAYER]:
return 3 + VALUES[PLAYER]
elif OPPONENT == 'A':
if PLAYER == 'Z':
return 6 + VALUES[PLAYER]
else:
return 0 + VALUES[PLAYER]
elif OPPONENT == 'B':
if PLAYER == 'X':
return 6 + VALUES[PLAYER]
else:
return 0 + VALUES[PLAYER]
elif OPPONENT == 'C':
if PLAYER == 'Y':
return 6 + VALUES[PLAYER]
else:
return 0 + VALUES[PLAYER]
SCORES = []
for i in data:
SCORES.append(rps(i))
print(sum(SCORES))
idk what i am doing wrong
oh wait nvm
e its wrong still
have you tried testing against the test input?
Similar to my strategy.
def part1_engine(turn):
d = dict(enumerate("AX BY CZ".split(), start=1))
convert = lambda x: next(k for k, v in d.items() if x.upper() in v)
a, b = map(convert, turn.split())
return b + [0, 3, 6][(b - a + 1) % 3]
def part2_engine(turn):
d = dict(zip("XYZ", (0, 3, 6)))
d |= dict(zip("ABC", range(1, 4)))
a, b = map(d.get, turn.split())
return b + (b//3+a+1) % 3 + 1
def game(data, engine):
return sum(map(engine, data.splitlines()))
print( game(INPUT, part1_engine) )
print( game(INPUT, part2_engine) )
reduced version -
def part1_engine(turn):
d = {
'X': 1, 'A': 1,
'Y': 2, 'B': 2,
'Z': 3, 'C': 3
}
a, b = map(d.get, turn.split())
return b + [0, 3, 6][(b - a + 1) % 3]
def part2_engine(turn):
d = {
'X': 0, 'A': 1,
'Y': 3, 'B': 2,
'Z': 6, 'C': 3
}
a, b = map(d.get, turn.split())
return b + (b//3+a+1) % 3 + 1
def game(data, engine):
return sum(map(engine, data.upper().splitlines()))
print( game(INPUT, part1_engine) )
print( game(INPUT, part2_engine) )
Hey @muted plover!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
what the hell did i do wrong? https://paste.pythondiscord.com/orepamagif
i've spent 3-4 hrs on this
def equi(x, y):
table = { 'A': {'X': 3, 'Y': 4, 'Z': 8}, 'B': {'X': 1, 'Y': 5, 'Z': 9}, 'C': {'X': 2, 'Y': 6, 'Z': 7}}
return table[x][y]
with open('aoc2.txt', 'r') as lines:
inputs = list(map(lambda line: line.rstrip().split(' '), lines))
result = sum(map(lambda x: equi(x[0], x[1]), inputs))
print(result)```
Basically there's pre calculated table. Only downside that it differs between 2 parts.