import java.util.Scanner; import java.lang.Math; class PowerIteration{ public static void main(String args[]){ Scanner scanner = new Scanner(System.in); int N,M; System.out.println("Enter Number of Nodes and Edges : "); N = scanner.nextInt(); M = scanner.nextInt(); PageRank pg = new PageRank(N,M); pg.input(); //-- iterate 50 times or until no difference between two iteration. for(int i = 0; i < 50; i++){ pg.iteration(); System.out.println(i+" Iteration Done"); if(pg.stop()){ System.out.println("NO Differece between Iteration"); break; } } pg.showPageRank(); } } class PageRank{ int Node=100,Edge=100; double epsilone = 0.0000000001; double[][] matrix = new double[Node][Edge]; double[] rank = new double[Node]; double[] old_rank = new double[Node]; Scanner scanner = new Scanner(System.in); PageRank(int N,int M){ Node = N; Edge = M; for(int i =0; i < Node; i++){ rank[i] = 1/(double)Node; //old_rank[i] = 1/ Node; } } void input(){ System.out.println("Input Value of Matrix\n"); for(int i = 0 ; i < Node; i++){ for(int j =0; j < Node; j++){ System.out.print("Enter value for matrix["+i+"]["+j+"] : "); matrix[i][j] = scanner.nextDouble(); } } } void show(){ System.out.println("\nMatrix is :\n"); for(int i = 0; i < Node; i++){ for(int j = 0; j < Node; j++){ System.out.print(matrix[i][j]+" "); } System.out.println(); } } boolean stop(){ for(int i = 0; i < Node; i++){ if( Math.abs( rank[i] - old_rank[i]) < epsilone ) continue; else return false; } return true; } void iteration(){ double[] product = new double[Node]; for(int i = 0; i < Node; i++){ old_rank[i] = rank[i]; product[i] = 0; //System.out.print(rank[i]); } //--multiply for(int i =0; i < Node; i++){ for(int j = 0; j < Node; j++){ product[i] += rank[j] * matrix[i][j]; } } //System.out.print("Now Rank is : "); for(int i =0 ; i < Node; i++){ rank[i] = product[i]; //System.out.print(product[i]+" "); } } void showPageRank(){ System.out.println("Page Rank is:\n"); for(int i = 0; i < Node; i++){ System.out.println("["+rank[i]+"]"); } } }