forked from prashantkalokhe/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ROUND OFF MATRIX.c
95 lines (91 loc) · 2.27 KB
/
ROUND OFF MATRIX.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
// Consider an n × n matrix A = (aij), each of whose elements aij is a nonnegative real
// number, and suppose that each row and column of A sums to an integer value. We wish
// to replace each element aij with either aij or aij without disturbing the row and
// column sums. Here is an example:
// Write a program by defining an user defined function that is used to produce the rounded matrix
// as described in the above example. Find out the time complexity of your algorithm/function.
#include<stdio.h>
#include<math.h>
#include<time.h>
float M[4][4];
float floatA[5][5];
float sum_row[5];
float sum_col[5];
float A[5][5];
int n;
void displayinitial() {
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("%.1lf\t",A[i][j]);
}
printf("\n");
}
}
void displayfinal() {
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
int a = (int)A[i][j];
printf("%d\t",a);
}
printf("\n");
}
}
void FloatSum() {
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
floatA[i][j]=A[i][j]-(int)A[i][j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
sum_row[i]=(sum_row[i]+floatA[i][j]);
}
sum_row[i]=round(sum_row[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
sum_col[i]=(sum_col[i]+floatA[j][i]);
}
sum_col[i]=round(sum_col[i]);
}
}
void algo() {
printf("\n");
for(int w=0;w<n;w++){
for(int q=0;q<n;q++){
if(sum_col[q]>0 && sum_row[w]>0){
A[w][q]=ceil(A[w][q]);
sum_col[q]=sum_col[q]-1;
sum_row[w]=sum_row[w]-1;
}
else A[w][q]=floor(A[w][q]);
}
}
}
void main() {
printf("\nEnter the size of Matrix upto 5x5\n");
scanf("%d",&n);
printf("Enter the values of array (rows followed by columns)\n");
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++)
{
scanf("%f",&A[i][j]);
}
}
printf("\nEntered Matrix :\n ");
displayinitial();
FloatSum();
algo();
printf("\nFinal Matrix :\n");
displayfinal();
}