feat(01): Solved part 2

This commit is contained in:
Jiří Štefka 2023-12-11 04:23:14 +01:00
parent 6f9d90bf4d
commit c64b0d008c
Signed by: jiriks74
GPG key ID: 1D5E30D3DB2264DE
3 changed files with 88 additions and 15 deletions

View file

@ -6,35 +6,74 @@
* @author jiriks74
*/
#define _GNU_SOURCE
// #define _LINE_LEN (size_t *)100
#define _LINE_LEN 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* @brief
* param
* return
*/
int getNum(const char *line) {
char *str = (char *)line;
// Mapping of words to numeric representations
const char *numbers[] = {"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"};
const char *digits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
// Find first written number
char *smallestPos = strchr(str, *"\0");
int numAtSmallPos = -1;
for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++) {
char *pos = NULL;
char *written = strstr(str, numbers[i]);
char *digit = strstr(str, digits[i]);
if (written == NULL && digit == NULL)
continue;
if (written == NULL)
pos = digit;
else if (digit == NULL)
pos = written;
else
pos = digit < written ? digit : written;
if (pos < smallestPos) {
numAtSmallPos = i;
smallestPos = pos;
}
}
// Chen which was first and return it
return numAtSmallPos;
}
/**
* @brief Gets a calibration value from a line
* @param char* line containing the calibration value
* @return int the calibration value
*/
int getVal(char *str) {
int num = 0;
int lastNum = -1;
int getVal(const char *str) {
int result = 0;
int result2 = -1;
for (int i = 0; i < strlen(str); i++) {
if (str[i] >= *"0" && str[i] <= *"9") {
if (num == 0) {
num = (str[i] - 48) * 10;
int num = getNum(&str[i]);
if (num >= 0) {
if (result == 0) {
result = num * 10;
} else {
lastNum = str[i] - 48;
result2 = num;
}
}
}
if (lastNum == -1) {
num += num / 10;
if (result2 == -1) {
result += result / 10;
} else {
num += lastNum;
result += result2;
}
return num;
return result;
}
/**
@ -52,9 +91,10 @@ int main(int argc, char *argv[])
if (argc == 1) {
file = stdin;
} else {
file = fopen(argv[1], "r");
file = fopen(argv[1], "r"); // LCOV_EXCL_LINE
}
// LCOV_EXCL_START
if (file == NULL) {
if (argc > 1)
fprintf(stderr, "Could not open file '%s'\n", argv[1]);
@ -62,6 +102,7 @@ int main(int argc, char *argv[])
fprintf(stderr, "Couldn't open file\n");
exit(EXIT_FAILURE);
}
// LCOV_EXCL_STOP
char *line;
size_t len = 0;