· 6 years ago · Nov 27, 2019, 07:06 AM
1#include <cstdio>
2#include <cstdlib>
3#include <ctime>
4#include <cmath>
5#include <conio.h>
6
7using namespace std;
8
9typedef double **table;
10
11int makeTable(table &tab, int rows, int cols);
12/*
13Создает динамический массив указанных размеров
14Входные параметры: rows - количество строчек (положительное число)
15 cols - количество столбцов (положительное число)
16Выходные параметры: tab - ссылка на переменную типа table, являющуюся указателем на указатель(2D массивом)
17Возвращает 0 если все хорошо.
18Возвращает 1 если размеры (cols / rows) указаны некорректно.
19*/
20
21void fillTable(table &tab, int rows, int cols, int isRand);
22/*
23Заполняет динамический массив указанных размеров
24Получаемые параметры как у makeTable, + входной isRand
25 isRand должен быть равен или 0, или 1 для того чтобы программа сделала хоть что-то.
26 если isRand == 0, то программа просит пользователя ввести значение в каждую ячейку вручную.
27 если isRand == 1, то программа заполняет массив случайными величинами.
28*/
29
30void outputTable(table &tab, int rows, int cols);
31/*
32Выводит массив на экран
33Получаемые параметры как у makeTable.
34*/
35
36void delTable(table &tab, int &rows, int &cols);
37/*
38Освобождает память из под динамического массива.
39Входных параметров нет.
40Выходные параметры: tab - ссылка на переменную типа table, являющуюся указателем на указатель(2D массивом)
41 rows - ссылка на количество строк в этом массиве, при выполнении программы зануляется
42 cols - ссылка на количество столбцов в этом массиве, при выполнении программы зануляется
43*/
44
45void computeTable(table &tab, int rows, int cols, double &result);
46/*
47Вычисляет наименьшую сумму абсолютных величин среди строк, в которых содержится больше всего нулей
48Входные параметры: rows - количество строчек (положительное число)
49 cols - количество столбцов (положительное число)
50Выходные параметры: tab - ссылка на переменную типа table, являющуюся указателем на указатель(2D массивом)
51 result - ссылка на переменную, изменяется программой. Результат
52*/
53
54//void testProg();
55
56
57int main()
58{
59 //testProg();
60
61 table tab;
62 int rows = 0;
63 int cols = 0;
64 char c = 'f';
65 char p[200];
66 FILE *f;
67 bool isFilled = false;
68 bool exists = false;
69 double result = 0;
70
71 while (c != '8')
72 {
73 if (c == '1')
74 {
75 if (exists)
76 {
77 delTable(tab, rows, cols);
78 isFilled = false;
79 }
80 while (rows <= 0) {
81 printf("Input positive number of rows\n");
82 scanf_s("%d", &rows);
83 }
84 while (cols <= 0) {
85 printf("Input positive number of cols\n");
86 scanf_s("%d", &cols);
87 }
88 makeTable(tab, rows, cols);
89 exists = true;
90 }
91 else if (c == '2')
92 {
93 if (exists)
94 {
95 delTable(tab, rows, cols);
96 }
97 printf("Input path to a file, for example \"C:\\Program Files\\table1.txt\"\n"\
98 "First two numbers in txt are numbers of ROWS and COLS,\n"\
99 "third number is if it will be filled with random number or not (1 = yes, 0 = no),\n"\
100 "other numbers will be inputed into the table if 3rd value was 0\n"\
101 "if there\'s not enough numbers to fill table remaining will become zeros.\n");
102 scanf_s("%s", &p, 200);
103 do
104 {
105 f = fopen(p, "r");
106 if (!f)
107 {
108 printf("Seems that the file doesn't exist.\n"\
109 "1. to try again.\n"\
110 "2. to return to previous menu.\n");
111 while (c != '1' && c != '2')
112 c = _getch();
113 }
114 } while (!f && c == '1');
115 do
116 {
117
118 } while (!feof(f));
119 }
120 else if (c == '3')
121 {
122 isFilled = true;
123 fillTable(tab, rows, cols, 0);
124 }
125 else if (c == '4')
126 {
127 isFilled = true;
128 fillTable(tab, rows, cols, 1);
129 }
130 else if (c == '5')
131 {
132 outputTable(tab, rows, cols);
133 }
134 else if (c == '6')
135 {
136 exists = false;
137 isFilled = false;
138 delTable(tab, rows, cols);
139 }
140 else if (c == '7')
141 {
142 computeTable(tab, rows, cols, result);
143 printf("result = %.4lf\n", result);
144 }
145 c = 'f';
146
147 if (!exists)
148 {
149 printf("Table does not exist.\n"\
150 "1. to create new table manually.\n"\
151 "2. to create new table from file.\n"\
152 "3. to exit.\n");
153 while (c != '1' && c != '3')
154 c = _getch();
155 if (c == '3')
156 c = '8';
157 }
158 else
159 {
160 if (!isFilled)
161 {
162 printf("Seems that your table is not filled.\n"\
163 "1. to fill it manually.\n"\
164 "2. to fill it with random values.\n"\
165 "3. to exit.\n");
166 while (c != '1' && c != '2' && c != '3')
167 c = _getch();
168 if (c == '1')
169 c = '3';
170 else if (c == '2')
171 c = '4';
172 else if (c == '3')
173 c = '7';
174 }
175 else
176 {
177 printf("Table exists and filled.\n"\
178 "1. to create a new table.\n"\
179 "2. to create new table from file.\n"\
180 "3. to refill table manually.\n"\
181 "4. to refill table with random values.\n"\
182 "5. to output table.\n"\
183 "6. to delete table.\n"\
184 "7. to compute table.\n"\
185 "8. to exit\n");
186 while (c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8')
187 c = _getch();
188 }
189 }
190 //system("cls");
191 }
192
193 if (exists)
194 delTable(tab, rows, cols);
195
196 return 0;
197}
198
199int makeTable(table &tab, int rows, int cols)
200{
201 if (rows > 0 && cols > 0)
202 {
203 tab = new double*[rows];
204 for (int i = 0; i < rows; i++)
205 tab[i] = new double[cols];
206 return 0;
207 }
208 else
209 return 1;
210}
211
212void fillTable(table &tab, int rows, int cols, int isRand)
213{
214 double d;
215 double val;
216 int chnc;
217 int sgn;
218 srand(time(0));
219
220 for (int i = 0; i < rows; i++)
221 {
222 for (int j = 0; j < cols; j++)
223 {
224 if (isRand == 1)
225 {
226 d = rand();
227 tab[i][j] = rand();
228 sgn = rand() % 2;
229 chnc = rand() % 20;
230 if (chnc > 0)
231 tab[i][j] += d / RAND_MAX;
232 if (sgn == 1)
233 tab[i][j] *= -1;
234 }
235 else
236 {
237 printf("Table[%d][%d] = ", i, j);
238 scanf_s("%lf", &val);
239 tab[i][j] = val;
240 }
241 }
242 }
243 return;
244}
245
246void outputTable(table &tab, int rows, int cols)
247{
248 for (int i = 0; i < rows; i++)
249 {
250 for (int j = 0; j < cols; j++)
251 {
252 printf("%10.3lf ", tab[i][j]);
253 }
254 putchar('\n');
255 }
256 return;
257}
258
259void delTable(table &tab, int &rows, int &cols)
260{
261 for (int i = 0; i < rows; i++)
262 delete[] tab[i];
263 delete[] tab;
264 rows = 0;
265 cols = 0;
266 return;
267}
268
269void computeTable(table &tab, int rows, int cols, double &result)
270{
271 int maxzir = -1; // int maxzir = 0; // maxzir (max zeros in row)
272 double minsum = 0; // minsum
273 int zir;
274 double sum;
275 double eps = 1.0e-18;
276
277 //for (int j = 0; j < cols; j++)
278 // minsum += abs(tab[0][j]);
279
280 for (int i = 0; i < rows; i++)
281 {
282 zir = 0;
283 sum = 0;
284
285 for (int j = 0; j < cols; j++)
286 {
287 if (abs(tab[i][j]) < eps)
288 zir += 1;
289 else
290 sum += abs(tab[i][j]);
291 }
292
293 if (zir >= maxzir)
294 {
295 if (zir > maxzir)
296 {
297 maxzir = zir;
298 minsum = sum;
299 }
300 else
301 {
302 if (sum < minsum || minsum == -1)
303 minsum = sum;
304 }
305 }
306 }
307 result = minsum;
308
309 return;
310}