Skip to content

Instantly share code, notes, and snippets.

@tpoisseau
Created October 19, 2024 06:51
Show Gist options
  • Save tpoisseau/0d50a9a0015bc9d1eb000a4d674ceff4 to your computer and use it in GitHub Desktop.
Save tpoisseau/0d50a9a0015bc9d1eb000a4d674ceff4 to your computer and use it in GitHub Desktop.
C training
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char findFirstDigit(char *string, size_t length);
char findLastDigit(char *string, size_t length);
int main() {
FILE *pFile;
unsigned short lineMax = 255;
char line[lineMax];
pFile = fopen("./2023-01-1.txt", "r");
if (pFile == NULL) {
perror("Error opening file.");
return 1;
}
unsigned long long sum = 0;
while (fgets(line, lineMax, pFile)) {
size_t length = strlen(line);
char firstDigit = findFirstDigit(line, length);
char lastDigit = findLastDigit(line, length);
if (firstDigit == '\0')
continue;
unsigned short firstNumber = firstDigit - '0';
unsigned short lastNumber = lastDigit - '0';
unsigned short number = firstNumber * 10 + lastNumber;
sum += number;
// printf("%c%c | %d | %llu | %s", firstDigit, lastDigit, number, sum,
// line);
}
fclose(pFile);
printf("Result: %llu", sum);
return 0;
}
char findLastDigit(char *string, size_t length) {
char digit = '\0';
char item = '\0';
size_t index;
for (index = length; index >= 0; index--) {
item = string[index];
if (item < '0')
continue;
if (item > '9')
continue;
digit = item;
break;
}
return digit;
}
char findFirstDigit(char *string, size_t length) {
char digit = '\0';
char item = '\0';
size_t index;
for (index = 0; index < length; index++) {
item = string[index];
if (item < '0')
continue;
if (item > '9')
continue;
digit = item;
break;
}
return digit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment