-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku_validator.c
148 lines (137 loc) · 3.29 KB
/
sudoku_validator.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int x = 0, y = 0, z = 0;
int sudoku[9][9] = {
{7, 9, 2, 1, 5, 4, 3, 8, 6},
{6, 4, 3, 8, 2, 7, 1, 5, 9},
{8, 5, 1, 3, 9, 6, 7, 2, 4},
{2, 6, 5, 9, 7, 3, 8, 4, 1},
{4, 8, 9, 5, 6, 1, 2, 7, 3},
{3, 1, 7, 4, 8, 2, 9, 6, 5},
{1, 3, 6, 7, 4, 8, 5, 9, 2},
{9, 7, 4, 2, 1, 5, 6, 3, 8},
{5, 2, 8, 6, 3, 9, 4, 1, 7}};
/*Returns the current time in seconds*/
double get_time()
{
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
return now.tv_sec + now.tv_nsec * 1e-9;
}
/*Checking values in a row*/
void *checkRows(void *param)
{
for (int i = 0; i < 9; i++)
{
int visited[9] = {0};
for (int j = 0; j < 9; j++)
{
if (visited[sudoku[i][j] - 1] == 1) // Number j occurs more than once in a row
{
x = 1;
break;
}
else
{
visited[sudoku[i][j] - 1] = 1;
}
}
if (x == 1)
{
break;
}
}
// sleep(5) ;
return NULL;
}
/*Checking values in a column*/
void *checkColumns(void *param)
{
for (int j = 0; j < 9; j++)
{
int visited[9] = {0};
for (int i = 0; i < 9; i++)
{
if (visited[sudoku[i][j] - 1] == 1) // Number j occurs more than once in a column
{
y = 1;
break;
}
else
{
visited[sudoku[i][j] - 1] = 1;
}
}
if (y == 1)
{
break;
}
}
// sleep(5) ;
return NULL;
}
void *checkSubGrids(void *param)
{
for (int i = 0; i < 9; i += 3)
{
for (int j = 0; j < 9; j += 3)
{
int visited[9] = {0};
for (int k = i; k < i + 3; k++)
{
for (int l = j; l < j + 3; l++)
{
if (visited[sudoku[k][l] - 1] == 1) // Number j occurs more than once in a submatrix
{
z = 1;
break;
}
else
{
visited[sudoku[k][l] - 1] = 1;
}
}
if (z == 1)
{
break;
}
}
if (z == 1)
{
break;
}
}
if (z == 1)
{
break;
}
}
// sleep(5) ;
return NULL;
}
int main()
{
double time = get_time();
pthread_t tid1, tid2, tid3;
/*Creating three threads for checking three conditions*/
pthread_create(&tid1, NULL, checkRows, NULL);
pthread_create(&tid2, NULL, checkColumns, NULL);
pthread_create(&tid3, NULL, checkSubGrids, NULL);
/*Waiting for the threads to complete*/
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
if (x == 1 || y == 1 || z == 1) // If any of the conditions are violated
{
printf("Invalid solution. Please try again.\n");
}
else
{
printf("The given solution is valid.\n");
}
printf("time taken: %.6lf seconds\n", get_time() - time);
return 0;
}