Advertisement
musifter

AoC 2022, day 2 (C)

Dec 2nd, 2022 (edited)
1,006
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | Source Code | 0 0
  1. #include <stdio.h>
  2.  
  3. // return result of game (loss, draw, win) = (0,1,2)
  4. int game_result( int me, int elf ) {
  5.     // res is basically (me - elf) mod 3, BUT...
  6.     //    +1 to shift to loss as 0 instead of draw
  7.     //    +3 to keep +'ve for mod
  8.     return ((me - elf + 4) % 3);
  9. }
  10.  
  11. // return score for a move
  12. int move_score( int move ) {
  13.     return (move + 1);
  14. }
  15.  
  16. // return move to get result against elf
  17. int get_move( int result, int elf ) {
  18.     // res = (me - elf + 1) mod 3 (see game_result())
  19.     //  me = (res + elf - 1) mod 3
  20.     //     = (res + elf + 2) mod 3 (keep +'ve for mod)
  21.     return ((elf + result + 2) % 3);
  22. }
  23.  
  24. int main() {
  25.     char    line[10];
  26.  
  27.     int     part1 = 0;
  28.     int     part2 = 0;
  29.  
  30.     while (fgets( line, sizeof(line), stdin ) != NULL) {
  31.         int elf  = line[0] - 'A';   // convert elf move to [0,2]
  32.         int resp = line[2] - 'X';   // convert response to [0,2]
  33.  
  34.         // Part 1: take response as move to make
  35.         part1 += 3 * game_result( resp, elf ) + move_score( resp );
  36.  
  37.         // Part 2: response is result of game desired
  38.         part2 += 3 * resp + move_score( get_move( resp, elf ) );
  39.     }
  40.  
  41.     printf( "Part 1: %d\n", part1 );
  42.     printf( "Part 2: %d\n", part2 );
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement