sudoku: add line-grid parsing

This commit is contained in:
Bruno BELANYI 2020-12-21 15:52:39 +01:00
parent 4b6bf824e6
commit b7a9b706e0
2 changed files with 37 additions and 0 deletions

View file

@ -1,6 +1,7 @@
#include "sudoku.h"
#include <stdio.h>
#include <stdlib.h>
#define INPUT_PATTERN "%1d %1d %1d %1d %1d %1d %1d %1d %1d\n"
@ -35,3 +36,37 @@ bool parse_grid_str(struct sudoku *grid, const char *input) {
return true;
}
bool parse_line_file(struct sudoku *grid, FILE *input) {
if (!input || !grid)
return false;
char *line = NULL;
if (getline(&line, NULL, input) < 0)
return false;
bool ret = parse_line_str(grid, line);
free(line);
return ret;
}
bool parse_line_str(struct sudoku *grid, const char *input) {
if (!input || !grid)
return false;
for (size_t i = 0; i < 9; ++i) {
for (size_t j = 0; j < 9; ++j) {
char c = *(input++);
if (c >= '1' && c <= '9')
grid->grid[i][j] = c - '0';
else if (c == '.' || c == '0')
grid->grid[i][j] = 0;
else
return false;
}
}
return true;
}

View file

@ -10,5 +10,7 @@ struct sudoku {
bool parse_grid_file(struct sudoku *grid, FILE *input);
bool parse_grid_str(struct sudoku *grid, const char *input);
bool parse_line_file(struct sudoku *grid, FILE *input);
bool parse_line_str(struct sudoku *grid, const char *input);
#endif /* !SUDOKU_H */