AOC2023: Cleanup day1 code

This commit is contained in:
Bananymous 2023-12-01 13:31:55 +02:00
parent 6a7335e5c9
commit 70c224d8ea
1 changed files with 28 additions and 25 deletions

View File

@ -53,54 +53,57 @@ int puzzle2(FILE* fp)
{ {
int line_len = strlen(buffer); int line_len = strlen(buffer);
int digit = -1;
for (int i = 0; i < line_len; i++) for (int i = 0; i < line_len; i++)
{ {
int digit = -1;
if (isdigit(buffer[i])) if (isdigit(buffer[i]))
{
digit = buffer[i] - '0'; digit = buffer[i] - '0';
break; else
}
for (int j = 0; j < 10; j++)
{ {
if (line_len - i < strlen(str_digits[j])) for (int j = 0; j < 10; j++)
continue;
if (strncmp(buffer + i, str_digits[j], strlen(str_digits[j])) == 0)
{ {
digit = j; int str_len = strlen(str_digits[j]);
break; if (line_len - i < str_len)
continue;
if (strncmp(buffer + i, str_digits[j], str_len) == 0)
{
digit = j;
break;
}
} }
} }
if (digit != -1) if (digit != -1)
{
sum += 10 * digit;
break; break;
}
} }
sum += 10 * digit;
digit = -1;
for (int i = line_len - 1; i >= 0; i--) for (int i = line_len - 1; i >= 0; i--)
{ {
int digit = -1;
if (isdigit(buffer[i])) if (isdigit(buffer[i]))
{
digit = buffer[i] - '0'; digit = buffer[i] - '0';
break; else
}
for (int j = 0; j < 10; j++)
{ {
if (i < strlen(str_digits[j])) for (int j = 0; j < 10; j++)
continue;
if (strncmp(buffer + i - strlen(str_digits[j]), str_digits[j], strlen(str_digits[j])) == 0)
{ {
digit = j; int str_len = strlen(str_digits[j]);
break; if (i < str_len)
continue;
if (strncmp(buffer + i - str_len, str_digits[j], str_len) == 0)
{
digit = j;
break;
}
} }
} }
if (digit != -1) if (digit != -1)
{
sum += digit;
break; break;
}
} }
sum += digit;
} }
return sum; return sum;