Ryan is an engineer in the Sacramento Area with a focus in Python, Ruby, and Rust. Bash/Python Exercism mentor. Coding, physics, calculus, music, woodworking. Looking for work!
Pretty quick one today! I didn't have much problem, and once I realized that the seat ID was actually the index into a 1-D array of seats, I stopped writing my own custom seatID->index function 😂
Day5.h:
#ifndef AOC2020_DAY5_H
#define AOC2020_DAY5_H
/// Day 5: Binary Boarding/// /// Calculate Seat ID's from a binary division process.#include <stdlib.h>
/// Calculate the seat ID by parsing a 10-char FFBBFFBLRL seat string/// to a seat row/column. The seat ID is not only row * 8 + col, but/// also the index into a linearized array of seats which is nice.intseat_ID(constchar*seat);/// Run both parts for the day.intday5(void);#endif
Day5.c:
#include "Day5.h"
#include <stdio.h>
#include <stdbool.h>
#define ROWS 128
#define COLS 8
#define NUM_ROW_CHARS 7
#define NUM_COL_CHARS 3
intseat_ID(constchar*seat){intfront=0,left=0;intdepth=ROWS;intwidth=COLS;for(inti=0;i<NUM_ROW_CHARS;i++){depth>>=1;if(seat[i]=='B')front+=depth;}for(inti=NUM_ROW_CHARS;i<NUM_ROW_CHARS+NUM_COL_CHARS;i++){width>>=1;if(seat[i]=='R')left+=width;}returnfront*8+left;}/// Part 1: Calculate the highest seat ID in the list.staticintpart1(void){FILE*fp;fp=fopen("data/day5.txt","r");if(fp==NULL){printf("Couldn't open file.\n");exit(EXIT_FAILURE);}intmax_ID=0;charseat[11];while(fgets(seat,11,fp)){intthis_ID=seat_ID(seat);if(this_ID>max_ID)max_ID=this_ID;}fclose(fp);returnmax_ID;}/// Part 2: Find the only empty seat on the plane. Note: some seats/// are missing from the front and back of the grid.staticintpart2(void){boolseats[ROWS*COLS]={0};FILE*fp;fp=fopen("data/day5.txt","r");if(fp==NULL){printf("Couldn't open file.\n");exit(EXIT_FAILURE);}// Load all seats in as present.charseat[11];while(fgets(seat,11,fp)){seats[seat_ID(seat)]=true;}fclose(fp);// Run through non-present seats. Once we're into seats on the plane,// the first empty one is mine!boolinside_plane=false;for(inti=0;i<ROWS*COLS;i++){if(!inside_plane&&seats[i])inside_plane=true;if(inside_plane&&!seats[i])returni;}return-1;}intday5(void){printf("====== Day 5 ======\n");printf("Part 1: %d\n",part1());printf("Part 2: %d\n",part2());returnEXIT_SUCCESS;}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Pretty quick one today! I didn't have much problem, and once I realized that the seat ID was actually the index into a 1-D array of seats, I stopped writing my own custom seatID->index function 😂
Day5.h:
Day5.c: