#AoC 2022 | Day 2 | Solutions & Spoilers

1447 messages Β· Page 2 of 2 (latest)

light abyss
#

i disagree

#

rb is a part of how it works

brave grail
livid crescent
#

Can you explain this please?

brave grail
ionic summit
#

ValueError: too many values to unpack (expected 4)

#

doesn't work for me lol

#

.\d2cg.py < .\input2.txt

livid crescent
light abyss
#

including the newline

echo halo
#

I like that Part 2 is basically the opposite mapping

ionic summit
#

is rb read bytes? so its like... binary to start with which removes the use of ord?

brave grail
#

when file name in the shortest code is changed to input.txt it's 88 bytes so still 18 bytes away

brave grail
#

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

ionic summit
#

what is ~

light abyss
#

binary not

brave grail
ionic summit
#

ok fun, what's the j doing in there?

brave grail
ionic summit
#

uhh why is that needed?

#

oh is it to separate p1 and 2

brave grail
ionic summit
#

christ

brave grail
#

i have no idea how i still have a sane enough mind to explain since it's about to become midnight for me

echo halo
#

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)
light abyss
#

js?

ionic summit
echo halo
ionic summit
#

especially with how it works with signed ints

echo halo
#

let me make a Python solve

edgy sail
#

I used a class for today's challenge

brave grail
ionic summit
#

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?

brave grail
edgy sail
#

the not operator is only confusing because python has dynamic sized ints

light abyss
#

it is confusing

brave grail
edgy sail
#

What's confusing about "make all the 0's 1's and all the 1's 0's"

brave grail
ionic summit
#

ok. so you aren't using ~ for anything special other than shorthand for subtraction and -1

edgy sail
#

it's a binary operator. They need to have an understanding of binary math to understand binary operators

light abyss
#

oh i know what a not operator does to fixed size ints

#

well it's a unary operator πŸ™ƒ

#

but a bitwise unary operator

light abyss
#

It's just confusing with dynamic ints as you said.

brave grail
#

that's often how it's used in code golfing

edgy sail
#

bitwise is the word, yes. Binary actually just means 2

#

i.e. there's 2 values involved

light abyss
#

yeah

#
  • is a binary operator because it operates on 2 values
#

~ is not, because it operates on one

brave grail
#

like wrapping your head around the result or the implementation?

light abyss
#

And a python integer starts with an infinite number of 0s

brave grail
light abyss
#

Which it turns all into ones in theory

light abyss
#

but it doesn't operate on the actual physical representation either

echo halo
#

ported my solve to Python

brave grail
#

ok midnight hit and it sort of surprised me to suddenly see "3 December 2022" on my screen

light abyss
#

oh yeah that's always fun

#

4 pm here

brave grail
light abyss
#

well

#

thinking of what it's doing to the bits

#
>>> bin(5)
'0b101'
>>> bin(~5)
'-0b110'
echo halo
# brave grail well no

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

dark fernBOT
#

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);```
brave grail
#

this is how it does ~v

#

it's literally just -(v + 1)

ionic summit
#

wots the -1 for?

brave grail
echo halo
#

that's why Artemis was confused

brave grail
#

i mean for small numbers that fit in a 30-bit integer it just does a normal bitwise not

echo halo
#

yes, but that's not the confusing part

#

I didn't optimize for size, but I optimized for something else which I think people here might like

light abyss
#

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

echo halo
light abyss
#

exactly

echo halo
brave grail
brave grail
#

was it automated

ionic summit
#

i dont understand any of it. nice

echo halo
brave grail
echo halo
#

where

brave grail
echo halo
#

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)

brave grail
#

what's the original code

echo halo
#
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

edgy sail
rugged kestrel
#

But got to use match-case in actual code!

woeful tapir
#

My solution is hardcoded. I tried to be clever and decided I couldn't be bothered. Not gonna share because I'm so embarrassed.

versed kernel
#

Hello everyone!

proven vault
versed kernel
fallow sky
#

@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')))
versed kernel
#

I too am having a

decided I couldn't be bothered.
thing with me rn

proven vault
#

I too had that

#

I had 3 failures trying to use fancy modulo maths

versed kernel
proven vault
#

so I just also went for a less impressive solution in the end

versed kernel
proven vault
#

I coded it in the morning - still didn't help

#

if anything made it worse

#

I am not a morning person

versed kernel
#

just read the code above, yall have some seriously esoteric code

paper geyser
#
// 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
pulsar flame
#

never seen it before

versed kernel
pulsar flame
#

what does it do

versed kernel
pulsar flame
#

bet

versed kernel
#

πŸ‘Œ

pulsar flame
#

I seeee

#

tysm. Imma start usin it

verbal jetty
#
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?
still smelt
#

looks like a lot of things

#

tell me your thought process

echo halo
#

that's an important part of the problem

#

I don't understand what you are doing with the index

opaque thicket
#

basically mine kekw

verbal jetty
#

ok i misreaded

limpid flare
#
"""
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 ;-;

jagged flax
#

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")
verbal jetty
#

me trying to use lambda in 1 line to solve whole problem: πŸ€“

cinder spruce
#
# 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
verbal jetty
#
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
rugged kestrel
verbal jetty
#

yes i figured it out now

#

im so dumb 🀦

lofty geode
#

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

worthy magnet
#

that is an impressive number of lambda functions!

verbal jetty
#

wow 😡

#

basically this 🀣

worthy magnet
#

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]
verbal jetty
#

what does ```py
a[:,1]-23-a[:,0]

worthy magnet
#

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

verbal jetty
#

kill me i dont understand it πŸ”«

pale mist
#

bump, is it a good approach?

astral jasper
verbal jetty
#

im too dumb to understand numpy πŸ˜‚

astral jasper
verbal jetty
#

me goes offline and sleep because dont understand what is numpy multi-dimension indexing

solar glacier
#

list[1:2]

#

matrix[1:2, 2:3]

proven vault
#

Do you have the full code?

edgy umbra
#

sure heres the full function

#

hold on, im using wsl so pasting does not go smooth

edgy umbra
astral jasper
dark fernBOT
#

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.

astral jasper
#

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

edgy umbra
#

like this? ```py
for lines in file.seek(0):

astral jasper
#

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

edgy umbra
#

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

oblique fog
#

the later elifs will never happen?

#

because eg A X has already matched A

astral jasper
#

Also, a/b/c mens what elves showed. Your own score is dependent on x/y/z

edgy umbra
#

really? so I should replace abc with xyz

#

on the first 3 conditions

oblique fog
#

why does scores exist?

#

if there's no nested loops, you can just return sum at the end

edgy umbra
#

i just never refactored, i can take it out

oblique fog
#

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

astral jasper
#

Where you have A X, change elif to just if - that way those double letter conditions will be checked regardless of one-letter conditions

pine void
#

rock, paper, scissor, and cheat - 2star baby

oblique fog
pine void
#

rust match function

edgy umbra
#

Still too high

#

wait

#

im gonna try something

astral jasper
#

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

edgy umbra
#

omg

astral jasper
#
A Y
B X
C Z

This example was supposed to give 15

edgy umbra
#

I get 9

astral jasper
#

Did you fix what I said?

edgy umbra
#

believe so let me scan through

astral jasper
#

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

edgy umbra
wheat bison
#

when you paste part 1 into gpt3

#

that is scarily close

#

part 2

pine void
#

test it plz

coarse spoke
manic zealot
#

haha me who used a giant if statement

quick mist
#

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)

blissful sand
sterile forum
blissful sand
#

We will be, we are competing with bots . Good or bad?

#

I guess like chess or similar...

quiet tangle
solar prairie
#
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

verbal jetty
#
#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
still smelt
#

wow

edgy sail
#

aoc is turning into #esoteric-python

coarse spoke
#

sure is

#

especially with those answers from earlier

edgy sail
#

one liners aren't always best

#

Also, you can shorten it by using map

coarse spoke
#

πŸ™ƒ

edgy sail
#
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())
brave grail
#

the absurd amount of if[-elif]-else required in most solutions posted here makes me question the difficulty of this day

haughty folio
#

it's a remarkably simple problem

#

just fairly repetitive (at least with the naΓ―ve soluion? i've seen some clever ones)

wheat bison
scarlet latch
edgy sail
#

Because I copied that answer without understanding it

#

Don't worry, it isn't my code

worthy magnet
#

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

sleek wraith
#
print(sum("B XC YA ZA XB YC ZC XA YB Z".index(line.strip())//3+1 for line in open('input.txt')))```
solar prairie
edgy sail
dark fernBOT
#

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```
scarlet latch
edgy sail
#

I used no chained ifs πŸ™‚

#

well, there was one.

#

But it wasn't for who beat who

brave grail
#

i still have no idea how i managed to formulate it

edgy sail
#

arrange your enum in such a way that you can do it all based on the ordinal

brave grail
sleek wraith
edgy sail
#

the next enum will always beat the previous one. The first enum will beat the last. Vice versa for losing

brave grail
#

i remember being so worried about finding the answer much faster

#

like wtf did i do here

proven vault
#

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

sleek wraith
#

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

strong whale
#

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()
strong whale
# strong whale My smol brain solutions, at least they're one line ```py def day_2(): def pa...

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

tulip narwhal
tulip narwhal
strong whale
#

It's interesting to see all the different ways people solve the same problem

tulip narwhal
#

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

sleek wraith
strong whale
sturdy widget
#

did someone say "not the most legible code"?

tulip narwhal
#

lol i like how you give a spaghetti code warning

sturdy widget
#

It's not like the other one is any more readable either

tulip narwhal
#

I'm no better my code isn't any more readable

#

I feel like that's one of those please increment comments thats all πŸ™‚

sleek wraith
#

self: int πŸ₯΄

sturdy widget
#

I wasn't sure what else to call it

#

does it actually matter though?

sleek wraith
#

no. it's fine.

strong whale
#

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

sturdy widget
#

cough lanternfish cough

sleek wraith
tulip narwhal
strong whale
sleek wraith
#

yes. usually when code works it works. but sometimes the input doesn't contain all border cases.

tulip narwhal
#

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

strong whale
#

XD

#

Might as well just look up the answer at that point

tulip narwhal
#

yup, another person figured out how to do it in vbscript, I was impressed

sturdy widget
#

I tried learning vbscript once

#

and then I gave up in a week

tulip narwhal
#

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

brave grail
sturdy widget
#

it might be doable as a datapack function

#

but idk how you would take puzzle input

strong whale
#

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

blissful sand
wheat bison
#

copied and pasted the problems from AoC

#

and below i wrote something like β€œwrite code to solve this problem”

quartz trout
#
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

livid crescent
#

And the way it explains it

#

Exactly like a real human

heavy snow
#

Why isn’t my code working?

quartz trout
sleek wraith
#

AZ, BX, CY are the combinations where you lose the game.

dire kestrel
#

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

stark cave
#

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

verbal jetty
#

just some if else statements

median badge
#

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"))
proven vault
#

Second two are more what I’d expect

median badge
proven vault
#

Tbh dictionaries. Map a string to one of the other two enum members

median badge
#

Ok yea that would work also. Thanks

spark egret
pale hearth
#

Peak

#

Lollllll fuck this part 2 got me leaving

lofty obsidian
#

you could use match for this!

#

it wouldn't be as concise, but whatever

copper bronze
#
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

cloud sleet
#

The inputs are all different

copper bronze
#

ah i se

#

anyway, any ideas why this is wrong?>

#

it works for the test input

cloud sleet
#

I'm not sure, sorry

proven vault
copper bronze
#

one

proven vault
#

i can never quite tell with the golfed solutions

copper bronze
#

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)
proven vault
#

does it work?

copper bronze
#

nope

proven vault
#

lol

copper bronze
#

could you run the second version

#

on your input

#

and see if it is correct?

proven vault
#

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

copper bronze
#

yeah

#

use +26 now?

proven vault
#

run A Y on it

#

ok, looks better for AY

copper bronze
#

okay got it :)

#

+26 worked

vale tapir
pale hearth
#

Aim was unreadability

#

Although pinned soln bests me

lofty obsidian
#

ah fuck, I forgot to push mine to github

#

I got to use match for something, at least

pale hearth
#

I like making oneliners just for the fun

#

Its formatted onto multiple but the spirits there

languid fox
#

I feel like my answer for day 2 is very... organic

proven vault
languid fox
#
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

latent garnet
#

If you kept going with the dicts this would decrease your code by like 90%

languid fox
#

I only started today, so I got an answer and moved on, I'll try editing day 1 and 2 tomorrow and like

hoary viper
#
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

earnest finch
#
# 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()
sleek wraith
# copper bronze what are these long strings?

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.

viral bluff
#

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.

manic gazelle
minor geyser
proven vault
proven vault
verbal jetty
#

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

copper bronze
#

πŸ’€

chrome vine
#

so behind on aoc πŸ˜” but had an amazing camp this weekend, so works lol

minor geyser
edgy sail
#

I also used enums

jovial shore
#
#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

pale hearth
verbal jetty
#

lol

dim oasis
#
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

proven vault
desert mason
#
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) )
desert mason
# desert mason ```py def part1_engine(turn): d = dict(enumerate("AX BY CZ".split(), start=1...

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

dark fernBOT
muted plover
#

i've spent 3-4 hrs on this

livid crescent
#

Day two was super fun

trail estuary
#
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.