Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathPageRank.java
More file actions
Latest commit
307 lines (276 loc) · 10.2 KB
/
Copy pathPageRank.java
File metadata and controls
307 lines (276 loc) · 10.2 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
packagecom.thealgorithms.others;
importjava.util.Scanner;
/**
* PageRank Algorithm Implementation
*
* <p>
* The PageRank algorithm is used by Google Search to rank web pages in their
* search engine
* results. It was named after Larry Page, one of the founders of Google.
* PageRank is a way of
* measuring the importance of website pages.
*
* <p>
* Algorithm: 1. Initialize PageRank values for all pages to 1/N (where N is the
* total number
* of pages) 2. For each iteration: - For each page, calculate the new PageRank
* by summing the
* contributions from all incoming links - Apply the damping factor: PR(page) =
* (1-d) + d *
* sum(PR(incoming_page) / outgoing_links(incoming_page)) 3. Repeat until
* convergence
*
* @see <a href="https://en.wikipedia.org/wiki/PageRank">PageRank Algorithm</a>
*/
publicfinalclassPageRank {
privatestaticfinalintMAX_NODES = 10;
privatestaticfinaldoubleDEFAULT_DAMPING_FACTOR = 0.85;
privatestaticfinalintDEFAULT_ITERATIONS = 2;
privateint[][] adjacencyMatrix;
privatedouble[] pageRankValues;
privateintnodeCount;
/**
* Constructor to initialize PageRank with specified number of nodes
*
* @param numberOfNodes the number of nodes/pages in the graph
* @throws IllegalArgumentException if numberOfNodes is less than 1 or greater
* than MAX_NODES
*/
publicPageRank(intnumberOfNodes) {
if (numberOfNodes < 1 || numberOfNodes > MAX_NODES) {
thrownewIllegalArgumentException("Number of nodes must be between 1 and " + MAX_NODES);
}
this.nodeCount = numberOfNodes;
this.adjacencyMatrix = newint[MAX_NODES][MAX_NODES];
this.pageRankValues = newdouble[MAX_NODES];
}
/**
* Default constructor for interactive mode
*/
publicPageRank() {
this.adjacencyMatrix = newint[MAX_NODES][MAX_NODES];
this.pageRankValues = newdouble[MAX_NODES];
}
/**
* Main method for interactive PageRank calculation
*
* @param args command line arguments (not used)
*/
publicstaticvoidmain(String[] args) {
try (Scannerscanner = newScanner(System.in)) {
System.out.print("Enter the Number of WebPages: ");
intnodes = scanner.nextInt();
PageRankpageRank = newPageRank(nodes);
System.out.println("Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: ");
for (inti = 1; i <= nodes; i++) {
for (intj = 1; j <= nodes; j++) {
intvalue = scanner.nextInt();
pageRank.setEdge(i, j, value);
}
}
pageRank.calculatePageRank(nodes, DEFAULT_DAMPING_FACTOR, DEFAULT_ITERATIONS, true);
}
}
/**
* Sets an edge in the adjacency matrix
*
* @param from source node (1-indexed)
* @param to destination node (1-indexed)
* @param value 1 if edge exists, 0 otherwise
*/
publicvoidsetEdge(intfrom, intto, intvalue) {
if (from == to) {
adjacencyMatrix[from][to] = 0; // No self-loops
} else {
adjacencyMatrix[from][to] = value;
}
}
/**
* Sets the adjacency matrix for the graph
*
* @param matrix the adjacency matrix (1-indexed)
*/
publicvoidsetAdjacencyMatrix(int[][] matrix) {
for (inti = 1; i <= nodeCount; i++) {
for (intj = 1; j <= nodeCount; j++) {
setEdge(i, j, matrix[i][j]);
}
}
}
/**
* Gets the PageRank value for a specific node
*
* @param node the node index (1-indexed)
* @return the PageRank value
*/
publicdoublegetPageRank(intnode) {
if (node < 1 || node > nodeCount) {
thrownewIllegalArgumentException("Node index out of bounds");
}
returnpageRankValues[node];
}
/**
* Gets all PageRank values
*
* @return array of PageRank values (1-indexed)
*/
publicdouble[] getAllPageRanks() {
returnpageRankValues.clone();
}
/**
* Calculates PageRank using the default damping factor and iterations
*
* @param totalNodes the total number of nodes
* @return array of PageRank values
*/
publicdouble[] calculatePageRank(inttotalNodes) {
returncalculatePageRank(totalNodes, DEFAULT_DAMPING_FACTOR, DEFAULT_ITERATIONS, false);
}
/**
* Calculates PageRank with custom parameters
*
* @param totalNodes the total number of nodes
* @param dampingFactor the damping factor (typically 0.85)
* @param iterations number of iterations to perform
* @param verbose whether to print detailed output
* @return array of PageRank values
*/
publicdouble[] calculatePageRank(inttotalNodes, doubledampingFactor, intiterations, booleanverbose) {
validateInputParameters(totalNodes, dampingFactor, iterations);
this.nodeCount = totalNodes;
doubleinitialPageRank = 1.0 / totalNodes;
if (verbose) {
System.out.printf("Total Number of Nodes: %d\tInitial PageRank of All Nodes: %.6f%n", totalNodes, initialPageRank);
}
initializePageRanks(totalNodes, initialPageRank, verbose);
performIterations(totalNodes, dampingFactor, iterations, verbose);
if (verbose) {
System.out.println("\nFinal PageRank:");
printPageRanks(totalNodes);
}
returnpageRankValues.clone();
}
/**
* Validates input parameters for PageRank calculation
*
* @param totalNodes the total number of nodes
* @param dampingFactor the damping factor
* @param iterations number of iterations
* @throws IllegalArgumentException if parameters are invalid
*/
privatevoidvalidateInputParameters(inttotalNodes, doubledampingFactor, intiterations) {
if (totalNodes < 1 || totalNodes > MAX_NODES) {
thrownewIllegalArgumentException("Total nodes must be between 1 and " + MAX_NODES);
}
if (dampingFactor < 0 || dampingFactor > 1) {
thrownewIllegalArgumentException("Damping factor must be between 0 and 1");
}
if (iterations < 1) {
thrownewIllegalArgumentException("Iterations must be at least 1");
}
}
/**
* Initializes PageRank values for all nodes
*
* @param totalNodes the total number of nodes
* @param initialPageRank the initial PageRank value
* @param verbose whether to print output
*/
privatevoidinitializePageRanks(inttotalNodes, doubleinitialPageRank, booleanverbose) {
for (inti = 1; i <= totalNodes; i++) {
pageRankValues[i] = initialPageRank;
}
if (verbose) {
System.out.println("\nInitial PageRank Values, 0th Step");
printPageRanks(totalNodes);
}
}
/**
* Performs the iterative PageRank calculation
*
* @param totalNodes the total number of nodes
* @param dampingFactor the damping factor
* @param iterations number of iterations
* @param verbose whether to print output
*/
privatevoidperformIterations(inttotalNodes, doubledampingFactor, intiterations, booleanverbose) {
for (intiteration = 1; iteration <= iterations; iteration++) {
double[] tempPageRank = storeCurrentPageRanks(totalNodes);
calculateNewPageRanks(totalNodes, tempPageRank);
applyDampingFactor(totalNodes, dampingFactor);
if (verbose) {
System.out.printf("%nAfter %d iteration(s)%n", iteration);
printPageRanks(totalNodes);
}
}
}
/**
* Stores current PageRank values in a temporary array
*
* @param totalNodes the total number of nodes
* @return temporary array with current PageRank values
*/
privatedouble[] storeCurrentPageRanks(inttotalNodes) {
double[] tempPageRank = newdouble[MAX_NODES];
for (inti = 1; i <= totalNodes; i++) {
tempPageRank[i] = pageRankValues[i];
pageRankValues[i] = 0;
}
returntempPageRank;
}
/**
* Calculates new PageRank values based on incoming links
*
* @param totalNodes the total number of nodes
* @param tempPageRank temporary array with previous PageRank values
*/
privatevoidcalculateNewPageRanks(inttotalNodes, double[] tempPageRank) {
for (inttargetNode = 1; targetNode <= totalNodes; targetNode++) {
for (intsourceNode = 1; sourceNode <= totalNodes; sourceNode++) {
if (adjacencyMatrix[sourceNode][targetNode] == 1) {
intoutgoingLinks = countOutgoingLinks(sourceNode, totalNodes);
if (outgoingLinks > 0) {
pageRankValues[targetNode] += tempPageRank[sourceNode] / outgoingLinks;
}
}
}
}
}
/**
* Applies the damping factor to all PageRank values
*
* @param totalNodes the total number of nodes
* @param dampingFactor the damping factor
*/
privatevoidapplyDampingFactor(inttotalNodes, doubledampingFactor) {
for (inti = 1; i <= totalNodes; i++) {
pageRankValues[i] = (1 - dampingFactor) + dampingFactor * pageRankValues[i];
}
}
/**
* Counts the number of outgoing links from a node
*
* @param node the source node (1-indexed)
* @param totalNodes total number of nodes
* @return the count of outgoing links
*/
privateintcountOutgoingLinks(intnode, inttotalNodes) {
intcount = 0;
for (inti = 1; i <= totalNodes; i++) {
if (adjacencyMatrix[node][i] == 1) {
count++;
}
}
returncount;
}
/**
* Prints the PageRank values for all nodes
*
* @param totalNodes the total number of nodes
*/
privatevoidprintPageRanks(inttotalNodes) {
for (inti = 1; i <= totalNodes; i++) {
System.out.printf("PageRank of %d: %.6f%n", i, pageRankValues[i]);
}
}
}