Skip to content

Commit

Permalink
day 01
Browse files Browse the repository at this point in the history
  • Loading branch information
oioki committed Dec 1, 2023
1 parent 113ec9e commit aad79a2
Show file tree
Hide file tree
Showing 6 changed files with 1,131 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
solution

106 changes: 106 additions & 0 deletions 01/01.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int calibration_value_mode1(char * s) {
int l = strlen(s);

int i = 0;
int j = l-1;

while ( !isdigit(s[i]) ) i++;
while ( !isdigit(s[j]) ) j--;

return 10 * (s[i] - '0') + (s[j] - '0');
}


const char * NUMBERS[] = {
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
};


int str_digit(char * s) {
for(int i=0; i<9; i++) {
if ( strncmp(NUMBERS[i], s, strlen(NUMBERS[i])) == 0 ) {
return i + 1;
}
}

return -1;
}


int calibration_value_mode2(char * s) {
int l = strlen(s);

int i = 0;
int d1 = 0;
int d2 = 0;
int tmp;

while ( i < l ) {
if ( isdigit(s[i]) ) {
d1 = s[i] - '0';
break;
}
else {
d1 = str_digit(&s[i]);
if (d1 != -1) break;
}

i++;
}

while ( i < l ) {
if ( isdigit(s[i]) ) {
d2 = s[i] - '0';
}
else {
tmp = str_digit(&s[i]);
if (tmp != -1) {
d2 = tmp;
}
}

i++;
}

return 10 * d1 + d2;
}


int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Usage: %s input.txt\n", argv[0]);
return 1;
}

int mode = 1;
if (argc > 2) {
mode = atoi(argv[2]);
}

FILE * f = fopen(argv[1], "r");
char s[255];

int result = 0;
do {
fscanf(f, "%s\n", s);
result += (mode == 1) ? calibration_value_mode1(s) : calibration_value_mode2(s);
} while (!feof(f));

printf("Answer: %d\n", result);

return 0;
}
12 changes: 12 additions & 0 deletions 01/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
all: tests run

solution: 01.c
cc 01.c -Wall -Wextra -o solution

run: solution
./solution input.txt 1
./solution input.txt 2

tests: solution
./solution example1.txt
./solution example2.txt 2
4 changes: 4 additions & 0 deletions 01/example1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
7 changes: 7 additions & 0 deletions 01/example2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
Loading

0 comments on commit aad79a2

Please sign in to comment.