RandomSurfer.java


Below is the syntax highlighted version of RandomSurfer.java from §2.2 Libraries.


/******************************************************************************
 *  Compilation:  javac RandomSurfer.java
 *  Execution:    java RandomSurfer trials
 *
 *  % java Transition < tinyGraph.txt | java RandomSurfer 1000000
 *   0.27297 0.26583 0.14598 0.24729 0.06793
 *
 ******************************************************************************/

public class RandomSurfer {
    public static void main(String[] args) {

        // number of moves
        int trials = Integer.parseInt(args[0]);

        // Transition matrix: p[i][j] = prob. that surfer moves from page i to
        double[][] p = StdArrayIO.readDouble2D();

        // dimension of the transition matrix
        int n = p.length;

        // freq[i] = # times surfer hits page i
        int[] freq = new int[n];

        // simulate the random surfer, starting at a random state
        int state = StdRandom.uniformInt(n);
        for (int t = 0; t < trials; t++) {
            state = StdRandom.discrete(p[state]);
            freq[state]++;
        }

        // Print page ranks.
        for (int i = 0; i < n; i++) {
            StdOut.printf("%8.5f", (double) freq[i] / trials);
        }
        StdOut.println();
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:17:58 EDT 2022.