%------------------------------------------------------------
% Tony Hyun Kim
% CS 246, PS #3, Problem 3(g)
%------------------------------------------------------------
clear all;

% Load the graph from the text file
source = 'graph.txt';
edges = load(source);
m = length(edges(:,1));

n = 100; % Number of nodes
global P;
P = zeros(n,n);

% Fill in the edges
for i = 1:m
    edge = edges(i,:);
    P(edge(1),edge(2)) = 1;
end

% Now renormalize the rows of P by degree
for i = 1:n
    p = P(i,:);
    P(i,:) = p/sum(p);
end

% Run Power Iteration
%------------------------------------------------------------
global eps;
eps = 0.2;
Niter = 40;
pis = zeros(1+Niter,n);
pi0 = 1/n*ones(1,n);
pis(1,:) = pi0;

ts = zeros(1,Niter);
for j = 1:Niter
    tic;
    pis(1+j,:) = eps*pi0+(1-eps)*pis(j,:)*P;
    ts(j) = toc;
end
fprintf('Power iteration: %d iterations, %.3f ms per iter, %.3f ms total\n',...
    Niter,mean(ts)*1e3,sum(ts)*1e3);

pi = pis(end,:); % The (approximate) PageRank distribution

% Sort the nodes
[~, rank] = sort(pi,'descend');