-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseArgs.c
104 lines (90 loc) · 2.63 KB
/
parseArgs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "parseArgs.h"
#include "error.h"
void parseArgs(Dance *d, int argc, char *argv[])
{
if(argc < 1)
numArgError();
if(!strcmp(argv[1], "s"))
d->problem = SUDOKU;
else if(!strcmp(argv[1], "s2"))
d->problem = SUDOKU2;
else if(!strcmp(argv[1], "q"))
d->problem = NQUEENS;
else if(!strcmp(argv[1], "sg"))
d->problem = SGEN;
else if(!strcmp(argv[1], "so"))
d->problem = SUDOKU_O;
else if(!strcmp(argv[1], "sgo"))
d->problem = SGEN_O;
else
arg1Error();
switch(d->problem)
{
case SUDOKU:
case SUDOKU2:
case SUDOKU_O: parseArgs_Sudoku(d, argc, argv); break;
case NQUEENS: parseArgs_NQueens(d, argc, argv); break;
case SGEN_O:
case SGEN: parseArgs_SGen(d, argc, argv); break;
}
}
/* a.out [s/s2] [file] */
void parseArgs_Sudoku(Dance *d, int argc, char *argv[])
{
int i, c, test;
Sudoku *s = malloc(sizeof(Sudoku));
char *buf = malloc(BUFSIZE*sizeof(char));
memset(buf, 0, BUFSIZE*sizeof(char));
if(argc != 3)
numArgError();
d->s = s;
s->boardFile = fopen(argv[2], "r+");
if(!s->boardFile)
fileError(argv[2]);
assert(fseek(s->boardFile, 0, SEEK_SET) == 0);
assert(2 == sscanf(argv[2], "tests/%dx%d.txt", &s->x, &s->y));
s->xy = s->x*s->y;
s->gridSize = s->xy*s->xy;
s->grid = calloc(s->gridSize, sizeof(int));
fgets(buf, BUFSIZE*sizeof(char), s->boardFile);
for(i = 0; i < s->gridSize; i++)
{
fgets(buf, BUFSIZE*sizeof(char), s->boardFile);
test = sscanf(buf, "%d", &c);
/*
board is invalid if sudoku numbers are not
within 0 to xy inclusive
*/
if(test != 1 || c < 0 || c > s->xy)
invalidSudokuBoard();
s->grid[i] = c;
}
free(buf);
}
/* a.out sg [file] [x] [y] */
void parseArgs_SGen(Dance *d, int argc, char *argv[])
{
Sudoku *s = malloc(sizeof(Sudoku));
if(argc != 5)
numArgError();
d->s = s;
s->boardFile = fopen(argv[2], "w+");
if(!s->boardFile)
fileError(argv[2]);
assert(fseek(s->boardFile, 0, SEEK_SET) == 0);
assert(1 == sscanf(argv[3], "%d", &s->x));
assert(1 == sscanf(argv[4], "%d", &s->y));
s->xy = s->x*s->y;
s->gridSize = s->xy*s->xy;
s->grid = calloc(s->gridSize, sizeof(int));
/* print board dimensions at top of file */
fprintf(d->s->boardFile, "%d %d\n", s->x, s->y);
}
/* a.out q [n] */
void parseArgs_NQueens(Dance *d, int argc, char *argv[])
{
if(argc != 3){
numArgError();}
if(1 != sscanf(argv[2], "%d", &d->nq))
invalidN_NQueens();
}