· 6 years ago · Dec 20, 2019, 07:06 AM
1#include <cstdio>
2#include <cstdlib>
3#include <ctime>
4#include <cmath>
5#include <cerrno>
6#include <conio.h>
7
8using namespace std;
9
10typedef double*** table;
11
12int makeTable(table &tab, int *rows, int *cols, int ind);
13/*
14Создает динамический массив указанных размеров
15Входные параметры: rows - количество строчек (положительное число)
16 cols - количество столбцов (положительное число)
17Выходные параметры: tab - ссылка на переменную типа table, являющуюся указателем на указатель(2D массивом)
18Возвращает 0 если все хорошо.
19Возвращает 1 если размеры (cols / rows) указаны некорректно.
20*/
21
22int fmakeTable(table &tab, int *rows, int *cols, char *name, int ind);
23
24
25void fillTable(table &tab, int *rows, int *cols, int isRand, int ind);
26/*
27Заполняет динамический массив указанных размеров
28Получаемые параметры как у makeTable, + входной isRand
29 isRand должен быть равен или 0, или 1 для того чтобы программа сделала хоть что-то.
30 если isRand == 0, то программа просит пользователя ввести значение в каждую ячейку вручную.
31 если isRand == 1, то программа заполняет массив случайными величинами.
32*/
33
34void outputTable(table &tab, int *rows, int *cols, int ind);
35/*
36Выводит массив на экран
37Получаемые параметры как у makeTable.
38*/
39
40void delTable(table &tab, int *rows, int *cols, int ind);
41/*
42Освобождает память из под динамического массива.
43Входных параметров нет.
44Выходные параметры: tab - ссылка на переменную типа table, являющуюся указателем на указатель(2D массивом)
45 rows - ссылка на количество строк в этом массиве, при выполнении программы зануляется
46 cols - ссылка на количество столбцов в этом массиве, при выполнении программы зануляется
47*/
48
49int computeTable(table& tab, int *rows, int *cols, double& result, int ind);
50/*
51Вычисляет наименьшую сумму абсолютных величин среди строк, в которых содержится больше всего нулей
52Входные параметры: rows - количество строчек (положительное число)
53 cols - количество столбцов (положительное число)
54Выходные параметры: tab - ссылка на переменную типа table, являющуюся указателем на указатель(2D массивом)
55 result - ссылка на переменную, изменяется программой. Результат
56*/
57
58void saveTable(table& tab, int *rows, int *cols, char *name, int ind);
59
60void clearStr(char* arr, int size);
61
62int main()
63{
64 table tab;
65 int *rows;
66 int *cols;
67 const int TABS = 8;
68 int tabs = 0;
69 int ind;
70 char c = 'f';
71 char name[200];
72 FILE* file;
73 bool isFilled = false;
74 bool exists = false;
75 double result = 0;
76 int fr = 0;
77
78 tab = new double** [TABS];
79 cols = new int[TABS];
80 rows = new int[TABS];
81
82 while (c != '8')
83 {
84 if (c == '1')
85 {
86 if (exists)
87 {
88 if (tabs == TABS)
89 {
90 printf("You need to delete one table in order to create a new one (you can save it).\n"\
91 "Which one it will be?");
92 for (int i = 1; i < tabs + 1; i++)
93 {
94 printf("Table NO. %d.\n", i);
95 }
96 while (ind < 1 && ind > tabs)
97 scanf_s("%d", &ind);
98 ind -= 1;
99 printf("Do you want to save it?\n"\
100 "1. yes\n"\
101 "2. no\n");
102 while (c != '1' && c != '2')
103 c = _getch();
104 if (c == '1')
105 {
106 clearStr(name, 200);
107 scanf_s("%s", name, 200);
108 saveTable(tab, rows, cols, name, ind);
109 delTable(tab, rows, cols, ind);
110 }
111 else
112 {
113 delTable(tab, rows, cols, ind);
114 }
115 }
116 else if (tabs = 0)
117 {
118 printf("No tables exist.\n"\
119 "");
120 }
121 }
122 while (rows <= 0) {
123 printf("Input positive number of rows\n");
124 scanf_s("%d", &rows);
125 }
126 while (cols <= 0) {
127 printf("Input positive number of cols\n");
128 scanf_s("%d", &cols);
129 }
130 makeTable(tab, rows, cols, ind);
131 exists = true;
132 }
133 else if (c == '2')
134 {
135 if (exists)
136 {
137 delTable(tab, rows, cols, ind);
138 }
139 printf("Input name of file, for example \"table1.txt\"\n"\
140 "First two numbers in txt are numbers of ROWS and COLS,\n"\
141 "other numbers will be inputed into the table.\n");
142 //"If there\'s not enough numbers to fill table remaining will become zeros.\n");
143 // 1 = Файл не существует
144 // 2 = недостаточно эллементов
145 // 3 = ошибка при чтении данных
146 // 4 = некорректные значения
147 scanf_s("%s", &name, 200);
148 fr = fmakeTable(tab, rows, cols, name);
149 c = '1';
150 while (fr != 0 && c == '1')
151 {
152 c = 'f';
153 if (fr == 1)
154 printf("Error! Seems that the file doesn't exist.\n");
155 //"1. to try again with other file.\n"\
156 //"2. to return to previous menu.\n");
157 else if (fr == 2)
158 printf("Error! There is not enough elements in a file!\n");
159 else if (fr == 3)
160 printf("Error occured while reading from a file.\n");
161 else if (fr == 4)
162 printf("Error! Inputed sizes are not correct!\n");
163 printf("1. to try again with other file.\n"\
164 "2. to return to previous menu.\n");
165 while (c != '1' && c != '2')
166 c = _getch();
167 if (c == '1')
168 {
169 printf("Input name of file, for example \"table1.txt\"\n"\
170 "First two numbers in txt are numbers of ROWS and COLS,\n"\
171 "other numbers will be inputed into the table.\n");
172 scanf_s("%s", &name, 200);
173 fr = fmakeTable(tab, rows, cols, name);
174 }
175 }
176 if (fr == 0)
177 {
178 exists = true;
179 isFilled = true;
180 }
181 c = 'f';
182 }
183 else if (c == '3')
184 {
185 isFilled = true;
186 fillTable(tab, rows, cols, 0);
187 }
188 else if (c == '4')
189 {
190 isFilled = true;
191 fillTable(tab, rows, cols, 1);
192 }
193 else if (c == '5')
194 {
195 outputTable(tab, rows, cols);
196 }
197 else if (c == '6')
198 {
199 exists = false;
200 isFilled = false;
201 delTable(tab, rows, cols);
202 }
203 else if (c == '7')
204 {
205 computeTable(tab, rows, cols, result);
206 printf("result = %.4lf\n", result);
207 }
208 c = 'f';
209
210 if (!exists)
211 {
212 printf("Table does not exist.\n"\
213 "1. to create new table manually.\n"\
214 "2. to create new table from file.\n"\
215 "3. to exit.\n");
216 while (c != '1' && c != '2' && c != '3')
217 c = _getch();
218 if (c == '3')
219 c = '8';
220 }
221 else
222 {
223 if (!isFilled)
224 {
225 printf("Seems that your table is not filled.\n"\
226 "1. to fill it manually.\n"\
227 "2. to fill it with random values.\n"\
228 "3. to exit.\n");
229 while (c != '1' && c != '2' && c != '3')
230 c = _getch();
231 if (c == '1')
232 c = '3';
233 else if (c == '2')
234 c = '4';
235 else if (c == '3')
236 c = '8';
237 }
238 else
239 {
240 printf("Table exists and filled.\n"\
241 "1. to create a new table.\n"\
242 "2. to create new table from file.\n"\
243 "3. to refill table manually.\n"\
244 "4. to refill table with random values.\n"\
245 "5. to output table.\n"\
246 "6. to delete table.\n"\
247 "7. to compute table.\n"\
248 "8. to exit\n");
249 while (c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8')
250 c = _getch();
251 }
252 }
253 //system("cls");
254 }
255
256 //if (exists)
257 // delTable(tab, rows, cols);
258
259 return 0;
260}
261
262int makeTable(table &tab, int *rows, int *cols, int ind)
263{
264 if (rows > 0 && cols > 0)
265 {
266 tab[ind] = new double* [rows[ind]];
267 for (int i = 0; i < rows[ind]; i++)
268 tab[ind][i] = new double[cols[ind]];
269 return 0;
270 }
271 else
272 return 1;
273}
274
275int fmakeTable(table& tab, int *rows, int *cols, char* name, int ind)
276{
277 FILE* file;
278 bool flag1 = true, flag2 = true;
279 int val = 0;
280 double dval = 0;
281 errno_t err1, err0 = fopen_s(&file, name, "r");
282 if (err0 != 0)
283 {
284 return 1; // 1 = Файл не существует
285 }
286 else
287 {
288 for (int i = 0; i < 2; i++)
289 {
290 err1 = fscanf_s(file, "%d", &val);
291 if (err1 == EOF) {
292 rows[ind] = 0;
293 cols[ind] = 0;
294 fclose(file);
295 return 2;
296 } // 2 = недостаточно эллементов
297 else if (err1 != 1) {
298 rows[ind] = 0;
299 cols[ind] = 0;
300 fclose(file);
301 return 3;
302 } // 3 = ошибка при чтении данных
303 else if (i == 0)
304 rows[ind] = val;
305 else
306 cols[ind] = val;
307 }
308 if (rows <= 0 || cols <= 0) {
309 rows = 0;
310 cols = 0;
311 fclose(file);
312 return 4; // 4 = некорректные значения
313 }
314 makeTable(tab, rows, cols, ind);
315 for (int i = 0; i < rows[ind]; i++)
316 {
317 for (int j = 0; j < cols[ind]; j++)
318 {
319 err1 = fscanf_s(file, "%lf", &dval);
320 if (err1 == EOF) {
321 delTable(tab, rows, cols, ind);
322 fclose(file);
323 return 2;
324 } // 2 = недостаточно эллементов
325 else if (err1 != 1) {
326 delTable(tab, rows, cols, ind);
327 fclose(file);
328 return 3;
329 } // 3 = ошибка при чтении данных
330 else
331 tab[ind][i][j] = dval;
332 }
333 }
334 fclose(file);
335 return 0;
336 }
337}
338
339void fillTable(table& tab, int *rows, int *cols, int isRand, int ind)
340{
341 double d;
342 double val;
343 int chncRat;
344 //int chncTen;
345 int sgn;
346 srand(time(0));
347
348 for (int i = 0; i < rows[ind]; i++)
349 {
350 for (int j = 0; j < cols[ind]; j++)
351 {
352 if (isRand == 1)
353 {
354 d = rand();
355 tab[ind][i][j] = rand();
356 sgn = rand() % 2;
357 chncRat = rand() % 20;
358 if (chncRat > 0)
359 tab[ind][i][j] += d / 876; //RAND_MAX;
360 if (sgn == 1)
361 tab[ind][i][j] *= -1;
362 }
363 else
364 {
365 printf("Table[%d][%d] = ", i, j);
366 scanf_s("%lf", &val);
367 tab[ind][i][j] = val;
368 }
369 }
370 }
371 return;
372}
373
374void outputTable(table& tab, int *rows, int *cols, int ind)
375{
376 for (int i = 0; i < rows[ind]; i++)
377 {
378 for (int j = 0; j < cols[ind]; j++)
379 {
380 printf("%10.3lf ", tab[ind][i][j]);
381 }
382 putchar('\n');
383 }
384 return;
385}
386
387void delTable(table& tab, int *rows, int *cols, int ind)
388{
389 if (rows[ind] <= 0 && cols[ind] <= 0)
390 {
391 for (int i = 0; i < rows[ind]; i++)
392 delete[] tab[i];
393 delete[] tab;
394 rows = 0;
395 cols = 0;
396 return;
397 }
398}
399
400int computeTable(table &tab, int *rows, int *cols, double &result, int ind)
401{
402 int cntr = 0, ind2 = 0, i = 0, j = 0, k = 0;
403 int* arr = new int[rows[ind]];
404
405 while (i < cols[ind])
406 {
407 while (j < rows[ind])
408 {
409 while (k < ind2)
410 {
411 if (tab[ind][j][i] == arr[k])
412 {
413 cntr += 1;
414 k = ind2;
415 j = rows[ind];
416 }
417 k += 1;
418 }
419 arr[ind2] = tab[ind][j][i];
420 j += 1;
421 ind2 += 1;
422 }
423 i += 1;
424 j = 0;
425 k = 0;
426 ind2 = 0;
427 }
428 /*
429 for (int i = 0; i < cols[ind]; i++)
430 {
431 for (int j = 0; j < rows[ind]; j++)
432 {
433 for (int k = 0; k < ind2; k++)
434 {
435 if (tab[ind][j][i] == arr[k])
436 {
437 cntr += 1;
438 i += 1;
439 j = 0;
440 k = ind2;
441 }
442 }
443 arr[ind2] = tab[ind][j][i];
444 ind2 += 1;
445 }
446 }
447 */
448 result = cntr;
449
450 return 0;
451}
452
453void saveTable(table& tab, int* rows, int* cols, char* name, int ind)
454{
455
456 return;
457}
458
459void clearStr(char* arr, int size)
460{
461 for (int i = 0; i < size; i++)
462 arr[i] = 0;
463
464 return;
465}