-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsparseMatrix.java
138 lines (137 loc) · 2.58 KB
/
sparseMatrix.java
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
import java.util.Scanner;
class sparse
{
int row;
int col;
int val;
sparse next;
static sparse head;
public sparse(int r,int c,int v)
{
this.row = r;
this.col = c;
this.val = v;
next = null;
}
}
public class sparseMatrix
{
int arr[][];
int n,non;
sparse res[];
static Scanner S = new Scanner(System.in);
public sparseMatrix(int N)
{
arr = new int[N][N];
n = N;
}
void insert()
{
for(int i = 0;i<this.n;i++)
{
for(int j = 0;j<this.n;j++)
{
System.out.println("Enter the value : ");
arr[i][j] = S.nextInt();
}
}
}
void display(int arr[][])
{
System.out.println("displaying matrix values ....");
for(int i = 0;i<this.n;i++)
{
for(int j = 0;j<this.n;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println("Memory utilization : "+this.n*this.n*4+" bytes");
}
void display(sparse head)
{
System.out.println("1d array representation....");
sparse t = head;
int i = 1;
while(t.next!=null)
{
System.out.println("Row : "+t.row+" Column : "+t.col+" Value : "+t.val);
t = t.next;
i++;
}
this.non = i;
System.out.println("Row : "+t.row+" Column : "+t.col+" Value : "+t.val);
System.out.println("Memory utilization : "+i*3*4+" bytes");
}
void convert() // converts 2 d array to array of linked list
{
for(int i = 0;i<this.n;i++)
{
for(int j = 0;j<this.n;j++)
{
if(arr[i][j]!=0)
{
if(sparse.head==null)
{
sparse.head = new sparse(i,j,arr[i][j]);
}
else
{
sparse t = sparse.head;
while(t.next!=null)
{
t = t.next;
}
sparse temp = new sparse(i,j,arr[i][j]);
t.next = temp;
}
}
}
}
display(sparse.head);
}
void transpose()
{
sparse t = sparse.head;
while(t.next!=null)
{
int temp = t.col;
t.col = t.row;
t.row = temp;
t = t.next;
}
int trans[][] = new int [this.n][this.n];
t = sparse.head;
while(t!=null)
{
for(int i = 0;i<this.n;i++)
{
for(int j = 0;j<this.n;j++)
{
if(t.row==i && t.col==j)
{
trans[i][j] = t.val;
}
else
{
continue;
}
}
}
t = t.next;
}
System.out.println("Transpose Matrix ....");
display(trans);
}
public static void main(String args[])
{
System.out.println("Enter the size of the matrix : ");
sparseMatrix sm = new sparseMatrix(S.nextInt());
sm.insert();
sm.display(sm.arr);
sm.convert();
sm.transpose();
S.close();
}
}