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