Advent of Code 2022 - Day 2

These are my solutions to Day 2 of the advent of code 2022. Today’s puzzle involved working out the score from a game of rock-paper-scissors by parsing a large text document, and then developed into a slightly more complicated variation in the second part. I solved the problem today using C.

{% highlight C %} #include<stdio.h>

int main(){ // First let’s open the file. FILE *fp; char moves[6]; long int grand_total; grand_total = 0; fp = fopen(“input”, “r”);

while(fgets(moves, 6, fp) != NULL){ char my_move; char their_move;

int my_score;
int their_score;

my_score = 0;
their_score = 0;

my_move= moves[2];
their_move = moves[0];
printf("%c", my_move);
switch(my_move){
case 'X':
  my_score = 1;
  break;
case 'Y':
  my_score = 2;
  break;
case 'Z':
  my_score = 3;
  break;
}
printf("%i", my_score);
printf("%c", their_move);
switch(their_move){
case 'A':
  their_score = 1;
  break;
case 'B':
  their_score = 2;
  break;
case 'C':
  their_score = 3;
  break;
}

if ((my_score - their_score > 0) & (my_score - their_score < 2)) {
  my_score += 6;
}
else if (my_score - their_score == -2){
  my_score += 6;
}
else if (my_score == their_score) {
  my_score += 3;
}
else {
  // They won
}

printf("%u\n", my_score);
grand_total += my_score;

}

fclose(fp); printf(“Grand total %ld”, grand_total); return 0; } {% endhighlight %}

{% highlight C %} #include<stdio.h>

int main(){ // First let’s open the file. FILE *fp; char moves[6]; long int grand_total; grand_total = 0; fp = fopen(“input”, “r”);

while(fgets(moves, 6, fp) != NULL){ char my_move; char their_move;

int my_score;
int their_score;

my_score = 0;
their_score = 0;

my_move= moves[2];
their_move = moves[0];

printf("%c", their_move);
switch(their_move){
case 'A':
  their_score = 1;
  break;
case 'B':
  their_score = 2;
  break;
case 'C':
  their_score = 3;
  break;
}

printf("%c", my_move);
switch(my_move){
case 'X':
  my_score = ((their_score - 1));
  break;
case 'Y':
  my_score = their_score;
  break;
case 'Z':
  my_score = (their_score + 1);
  break;
}
if (my_score == 0){
my_score = 3;
}
else if (my_score == 4){
  my_score = 1;
}
switch(my_move){
case 'X':
  break;
case 'Y':
  my_score += 3;
  break;
case 'Z':
  my_score += 6;
  break;
}
printf("%i\n", my_score);
grand_total += my_score;

}

fclose(fp); printf(“Grand total %ld”, grand_total); return 0; }

{% endhighlight %}