-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_mtx.c
More file actions
114 lines (95 loc) · 2.88 KB
/
validate_mtx.c
File metadata and controls
114 lines (95 loc) · 2.88 KB
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
105
106
107
108
109
110
111
112
113
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
typedef struct {
int row;
int col;
double val;
} triple;
int comp(const void *a, const void *b) {
triple *ta = (triple *)a;
triple *tb = (triple *)b;
if (ta->row != tb->row) {
return ta->row - tb->row;
}
return ta->col - tb->col;
}
bool validate_matrix(triple *entries, int nnz, int rows, int cols) {
for (int i = 0; i < nnz; i++) {
if (entries[i].row < 1 || entries[i].row > rows ||
entries[i].col < 1 || entries[i].col > cols) {
fprintf(stderr, "Error: Index out of bounds at entry %d: (%d, %d)\n",
i, entries[i].row, entries[i].col);
return false;
}
if (i > 0 && entries[i].row == entries[i - 1].row &&
entries[i].col == entries[i - 1].col) {
fprintf(stderr, "Error: Duplicate entry at (%d, %d)\n",
entries[i].row, entries[i].col);
return false;
}
}
return true;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <input_file> <output_file>\n", argv[0]);
return 1;
}
const char *input_file = argv[1];
const char *output_file = argv[2];
FILE *in = fopen(input_file, "r");
if (!in) {
fprintf(stderr, "Error: Cannot open input file %s\n", input_file);
return 1;
}
char line[8192];
while (fgets(line, sizeof(line), in)) {
if (line[0] != '%') {
break;
}
}
int rows, cols, nnz;
if (sscanf(line, "%d %d %d", &rows, &cols, &nnz) != 3) {
fprintf(stderr, "Error: Invalid header format\n");
fclose(in);
return 1;
}
triple *entries = (triple *)malloc(nnz * sizeof(triple));
if (!entries) {
fprintf(stderr, "Error: Memory allocation failed\n");
fclose(in);
return 1;
}
for (int i = 0; i < nnz; i++) {
if (fscanf(in, "%d %d %lf", &entries[i].row, &entries[i].col, &entries[i].val) != 3) {
fprintf(stderr, "Error: Invalid entry format at line %d\n", i + 2);
free(entries);
fclose(in);
return 1;
}
}
fclose(in);
// Sort entries by row and column
qsort(entries, nnz, sizeof(triple), comp);
// Validate the matrix
if (!validate_matrix(entries, nnz, rows, cols)) {
free(entries);
return 1;
}
FILE *out = fopen(output_file, "w");
if (!out) {
fprintf(stderr, "Error: Cannot open output file %s\n", output_file);
free(entries);
return 1;
}
fprintf(out, "%d %d %d\n", rows, cols, nnz);
for (int i = 0; i < nnz; i++) {
fprintf(out, "%d %d %.17f\n", entries[i].row, entries[i].col, entries[i].val);
}
fclose(out);
free(entries);
printf("Matrix validated and written to %s\n", output_file);
return 0;
}