02 Python

The assignment for the second day.

Input data: Input

We have lines with pairs of rock/paper/scissors in the input file. The first player have them labeled A, B, C, the second player have them labelled X, Y, Z.

# map the input letters into numbers
m1 = {
    "A": 1,
    "B": 2,
    "C": 3,
    "X": 1,
    "Y": 2,
    "Z": 3,
}

# for the second part we use slightly different mapping
m2 = dict(m1)
m2["X"] = 0
m2["Y"] = 3
m2["Z"] = 6

def first(txt):
    s = 0
    for line in txt:
        a, b = map(m1.get, line.rstrip().split())
        if a == b:
            s += 3+b
        elif a < b:
            if b-a>1:
                s += b
            else:
                s += 6+b
        elif a > b:
            if a-b>1:
                s += 6+b
            else:
                s += b
    print(s)

def second(txt):
    s = 0
    for line in txt:
        a, b = map(m2.get, line.rstrip().split())
        # always add the answering hand shape
        s += b
        if b == 3:
            # if we should draw, add the opponent's hand shape
            s += a
        elif b == 0:
            # if we should lose, we should use less powerful shape
            # 3 > 2, 2 > 1, 1 > 3
            if a>1:
                s += a-1
            else:
                s += 3
        elif b == 6:
            # for winning we need to use more powerful shape
            # 1 > 2, 2 > 3, 3 > 1
            if a<3:
                s += a+1
            else:
                s += 1
    print(s)

# when running as a script
if __name__ == "__main__":
    # read standard input and store it's lines to txt
    txt = sys.stdin.readlines()
    first(txt)
    second(txt)

The script is called like this:

cat 02_input.txt | python3 our_script.py

AWK again

We don’t need to differentiate between them so we can replace the labels with numbers 1, 2, 3:

The same task but again in awk, just for fun and comparison.

cat 02.txt | tr "ABCXYZ" "123123"

Next we are supposed to

Conditions to the rescue!

awk '{
  if ($1==$2) {
    s+=3+$2
  }
  else {
    if ($1<$2) {
      if ($2-$1>1) {
        s+=$2
      }
      else {
        s+=6+$2
      }
    }
    else {
      if ($1-$2>1) {
        s+=6+$2
      }
      else {
        s+=$2
      }
    }
  }
}
END {
  print s
}
'

Awk’s auto variables for columns are $1 and $2.

02B

We will now transform (tr) the input slightly differently:

cat input.txt | tr "ABCXYZ" "123036"

to match the resulting scores for losing, draw, winning.

The conditions now will be also different:

awk '{
  s+=$2
  if ($2=="3") {
    s+=$1
  }
  if ($2=="0") {
    if ($1>1) {
      s+=$1-1
    }
    else {
      s+=3
    }
  }
  if ($2=="6") {
    if ($1<3) {
      s+=$1+1
    }
    else {
      s+=1
    }
  }
}
END {
  print s
}

What I learned

published: 2022-12-02
last modified: 2023-01-21

https://vit.baisa.cz/notes/code/advent-of-code-2022/02/