Browse Source

day 5 challenge 2

master
Robby Zambito 2 months ago
parent
commit
7ca92ce564
1 changed files with 96 additions and 0 deletions
  1. +96
    -0
      day5/2/c/main.c

+ 96
- 0
day5/2/c/main.c View File

@ -0,0 +1,96 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
size_t getIdsAndMax(int **, int *, FILE *);
int main(int argc, char **argv) {
FILE *input = stdin;
int max = 0;
int *ids = NULL;
/* If a file is passed as an argument, use that instead of stdin */
if (argc >= 2)
input = fopen(argv[1], "r");
size_t idsLen = getIdsAndMax(&ids, &max, input);
/* 0...max are all the possible seats */
for (int i = 0; i < max; i++) {
bool isLeftInList = false, isRightInList = false, isTaken = false;
for (int j = 0; j < idsLen; j++) {
if (i == ids[j]) {
isTaken = true;
break;
}
if (i - 1 == ids[j])
isLeftInList = true;
if (i + 1 == ids[j])
isRightInList = true;
}
/* If the seat is not taken but the seats to the right and left are... */
if (!isTaken && isLeftInList && isRightInList)
printf("%d\n", i);
}
free(ids);
return EXIT_SUCCESS;
}
/* Returns the length of ids */
size_t getIdsAndMax(int **ids, int *max, FILE *input) {
/* Make sure ids is NULL before we start. */
free(*ids);
*ids = NULL;
*max = 0;
size_t idsLen = 0, idsCapacity = 10;
*ids = (int *) malloc(idsCapacity * sizeof(int *));
if (*ids == NULL) {
perror("Failled to malloc *ids");
exit(EXIT_FAILURE);
}
while (1) {
/* Double capacity of the id array */
if (idsCapacity == idsLen) {
idsCapacity *= 2;
int *temp = (int *) malloc(idsCapacity * sizeof(int *));
if (temp == NULL) {
perror("Failed to malloc temp");
exit(EXIT_FAILURE);
}
for (int i = 0; i < idsLen; i++)
temp[i] = (*ids)[i];
free(*ids);
*ids = temp;
}
char rowc[8], colc[4];
/* Scan 7 F/Bs into rowc, and 3 L/Rs into colc */
int scanned = fscanf(input, "%7[FB]%3[LR] ", rowc, colc);
if (scanned != EOF) {
int row = 0, col = 0, id = 0;
/* Interpret F/L as 0 and B/R as 1... convert input to int */
for (int i = 0; i < 7; i++) {
row |= (rowc[i] == 'B') << (6 - i);
col |= (i < 3 && (colc[i] == 'R')) << (2 - i);
}
/* Get seat ID and save if > max */
id = row * 8 + col;
*max = id > *max ? id : *max;
(*ids)[idsLen++] = id;
} else break;
}
return idsLen;
}

Loading…
Cancel
Save