示例#1
0
        /// <summary>
        /// Returns a wheel graph on <tt>V</tt> vertices.
        /// </summary>
        /// <param name="v">V the number of vertices in the wheel</param>
        /// <returns>a wheel graph on <tt>V</tt> vertices: a single vertex connected to every vertex in a cycle on <tt>V-1</tt> vertices</returns>
        public static Graph Wheel(int v)
        {
            if (v <= 1)
            {
                throw new ArgumentException("Number of vertices must be at least 2");
            }
            var g        = new Graph(v);
            var vertices = new int[v];

            for (var i = 0; i < v; i++)
            {
                vertices[i] = i;
            }
            StdRandom.Shuffle(vertices);

            // simple cycle on V-1 vertices
            for (var i = 1; i < v - 1; i++)
            {
                g.AddEdge(vertices[i], vertices[i + 1]);
            }
            g.AddEdge(vertices[v - 1], vertices[1]);

            // connect vertices[0] to every vertex on cycle
            for (var i = 1; i < v; i++)
            {
                g.AddEdge(vertices[0], vertices[i]);
            }

            return(g);
        }
示例#2
0
        /// <summary>
        /// Returns a random simple bipartite graph on <tt>V1</tt> and <tt>V2</tt> vertices,
        /// containing each possible edge with probability <tt>p</tt>.
        /// </summary>
        /// <param name="v1">V1 the number of vertices in one partition</param>
        /// <param name="v2">V2 the number of vertices in the other partition</param>
        /// <param name="p">p the probability that the graph contains an edge with one endpoint in either side</param>
        /// <returns>a random simple bipartite graph on <tt>V1</tt> and <tt>V2</tt> vertices, containing each possible edge with probability <tt>p</tt></returns>
        /// <exception cref="ArgumentException">if probability is not between 0 and 1</exception>
        public static Graph Bipartite(int v1, int v2, double p)
        {
            if (p < 0.0 || p > 1.0)
            {
                throw new ArgumentException("Probability must be between 0 and 1");
            }
            var vertices = new int[v1 + v2];

            for (var i = 0; i < v1 + v2; i++)
            {
                vertices[i] = i;
            }
            StdRandom.Shuffle(vertices);
            var g = new Graph(v1 + v2);

            for (var i = 0; i < v1; i++)
            {
                for (var j = 0; j < v2; j++)
                {
                    if (StdRandom.Bernoulli(p))
                    {
                        g.AddEdge(vertices[i], vertices[v1 + j]);
                    }
                }
            }
            return(g);
        }
示例#3
0
        /// <summary>
        /// Returns a random simple graph containing <tt>V</tt> vertices and <tt>E</tt> edges.
        /// </summary>
        /// <param name="v">V the number of vertices</param>
        /// <param name="e">E the number of edges</param>
        /// <returns> random simple graph on <tt>V</tt> vertices, containing a total of <tt>E</tt> edges</returns>
        /// <exception cref="ArgumentException">if no such simple graph exists</exception>
        public static Graph Simple(int v, int e)
        {
            if (e > (long)v * (v - 1) / 2)
            {
                throw new ArgumentException("Too many edges");
            }
            if (e < 0)
            {
                throw new ArgumentException("Too few edges");
            }
            var g   = new Graph(v);
            var set = new SET <EdgeU>();

            while (g.E < e)
            {
                var ve   = StdRandom.Uniform(v);
                var we   = StdRandom.Uniform(v);
                var edge = new EdgeU(ve, we);
                if ((ve == we) || set.Contains(edge))
                {
                    continue;
                }
                set.Add(edge);
                g.AddEdge(ve, we);
            }
            return(g);
        }
示例#4
0
        /// <summary>
        /// Returns a random simple digraph containing <tt>V</tt> vertices and <tt>E</tt> edges.
        /// </summary>
        /// <param name="v">V the number of vertices</param>
        /// <param name="e">E the number of vertices</param>
        /// <returns>a random simple digraph on <tt>V</tt> vertices, containing a total of <tt>E</tt> edges</returns>
        /// <exception cref="ArgumentException">if no such simple digraph exists</exception>
        public static Digraph Simple(int v, int e)
        {
            if (e > (long)v * (v - 1))
            {
                throw new ArgumentException("Too many edges");
            }
            if (e < 0)
            {
                throw new ArgumentException("Too few edges");
            }
            var g   = new Digraph(v);
            var set = new SET <EdgeD>();

            while (g.E < e)
            {
                var ve   = StdRandom.Uniform(v);
                var we   = StdRandom.Uniform(v);
                var edge = new EdgeD(ve, we);
                if ((ve != we) && !set.Contains(edge))
                {
                    set.Add(edge);
                    g.AddEdge(ve, we);
                }
            }
            return(g);
        }
示例#5
0
        /// <summary>
        /// Returns a random simple DAG containing <tt>V</tt> vertices and <tt>E</tt> edges.
        /// Note: it is not uniformly selected at random among all such DAGs.
        /// </summary>
        /// <param name="v">V the number of vertices</param>
        /// <param name="e">E the number of vertices</param>
        /// <returns>a random simple DAG on <tt>V</tt> vertices, containing a total of <tt>E</tt> edges</returns>
        /// <exception cref="ArgumentException">if no such simple DAG exists</exception>
        public static Digraph Dag(int v, int e)
        {
            if (e > (long)v * (v - 1) / 2)
            {
                throw new ArgumentException("Too many edges");
            }
            if (e < 0)
            {
                throw new ArgumentException("Too few edges");
            }
            var g        = new Digraph(v);
            var set      = new SET <EdgeD>();
            var vertices = new int[v];

            for (var i = 0; i < v; i++)
            {
                vertices[i] = i;
            }
            StdRandom.Shuffle(vertices);
            while (g.E < e)
            {
                var ve   = StdRandom.Uniform(v);
                var we   = StdRandom.Uniform(v);
                var edge = new EdgeD(ve, we);
                if ((ve < we) && !set.Contains(edge))
                {
                    set.Add(edge);
                    g.AddEdge(vertices[ve], vertices[we]);
                }
            }
            return(g);
        }
示例#6
0
    /**
     * Unit tests the {@code LinearProgramming} data type.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {

        StdOut.println("----- test 1 --------------------");
        test1();
        StdOut.println();

        StdOut.println("----- test 2 --------------------");
        test2();
        StdOut.println();

        StdOut.println("----- test 3 --------------------");
        test3();
        StdOut.println();

        StdOut.println("----- test 4 --------------------");
        test4();
        StdOut.println();

        StdOut.println("----- test random ---------------");
        int m = Integer.parseInt(args[0]);
        int n = Integer.parseInt(args[1]);
        double[] c = new double[n];
        double[] b = new double[m];
        double[][] A = new double[m][n];
        for (int j = 0; j < n; j++)
            c[j] = StdRandom.uniform(1000);
        for (int i = 0; i < m; i++)
            b[i] = StdRandom.uniform(1000);
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                A[i][j] = StdRandom.uniform(100);
        LinearProgramming lp = new LinearProgramming(A, b, c);
        test(A, b, c);
    }
示例#7
0
        /// <summary>
        /// Returns a uniformly random <tt>k</tt>-regular graph on <tt>V</tt> vertices
        /// (not necessarily simple). The graph is simple with probability only about e^(-k^2/4),
        /// which is tiny when k = 14.
        /// </summary>
        /// <param name="v">V the number of vertices in the graph</param>
        /// <param name="k"></param>
        /// <returns>a uniformly random <tt>k</tt>-regular graph on <tt>V</tt> vertices.</returns>
        public static Graph Regular(int v, int k)
        {
            if (v * k % 2 != 0)
            {
                throw new ArgumentException("Number of vertices * k must be even");
            }
            var g = new Graph(v);

            // create k copies of each vertex
            var vertices = new int[v * k];

            for (var vi = 0; vi < v; vi++)
            {
                for (var j = 0; j < k; j++)
                {
                    vertices[vi + v * j] = vi;
                }
            }

            // pick a random perfect matching
            StdRandom.Shuffle(vertices);
            for (var i = 0; i < v * k / 2; i++)
            {
                g.AddEdge(vertices[2 * i], vertices[2 * i + 1]);
            }
            return(g);
        }
示例#8
0
   /***************************************************************************
    *  Test client.
    ***************************************************************************/

    /**
     * Unit tests the {@code FFT} class.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);
        Complex[] x = new Complex[n];

        // original data
        for (int i = 0; i < n; i++) {
            x[i] = new Complex(i, 0);
            x[i] = new Complex(StdRandom.uniform(-1.0, 1.0), 0);
        }
        show(x, "x");

        // FFT of original data
        Complex[] y = fft(x);
        show(y, "y = fft(x)");

        // take inverse FFT
        Complex[] z = ifft(y);
        show(z, "z = ifft(y)");

        // circular convolution of x with itself
        Complex[] c = cconvolve(x, x);
        show(c, "c = cconvolve(x, x)");

        // linear convolution of x with itself
        Complex[] d = convolve(x, x);
        show(d, "d = convolve(x, x)");
    }
示例#9
0
    public static void main(String[] args) {

        // create random DAG with V vertices and E edges; then add F random edges
        int V = Integer.parseInt(args[0]);
        int E = Integer.parseInt(args[1]);
        int F = Integer.parseInt(args[2]);
        Digraph G = DigraphGenerator.dag(V, E);

        // add F extra edges
        for (int i = 0; i < F; i++) {
            int v = StdRandom.uniform(V);
            int w = StdRandom.uniform(V);
            G.addEdge(v, w);
        }

        StdOut.println(G);


        DirectedCycleX finder = new DirectedCycleX(G);
        if (finder.hasCycle()) {
            StdOut.print("Directed cycle: ");
            for (int v : finder.cycle()) {
                StdOut.print(v + " ");
            }
            StdOut.println();
        }

        else {
            StdOut.println("No directed cycle");
        }
        StdOut.println();
    }
示例#10
0
        /// <summary>
        /// Rearranges the array so that a[k] contains the kth smallest key;
        /// a[0] through a[k-1] are less than (or equal to) a[k]; and
        /// a[k+1] through a[N-1] are greater than (or equal to) a[k].
        /// </summary>
        /// <param name="a"></param>
        /// <param name="k"></param>
        /// <returns></returns>
        public static IComparable Select(IList <IComparable> a, int k)
        {
            if (k < 0 || k >= a.Count)
            {
                throw new IndexOutOfRangeException("Selected element out of bounds");
            }
            StdRandom.Shuffle(a);
            int lo = 0, hi = a.Count - 1;

            while (hi > lo)
            {
                var i = Partition(a, lo, hi);
                if (i > k)
                {
                    hi = i - 1;
                }
                else if (i < k)
                {
                    lo = i + 1;
                }
                else
                {
                    return(a[i]);
                }
            }
            return(a[lo]);
        }
示例#11
0
    /**
     * Unit tests the {@code AssignmentProblem} data type.
     * Takes a command-line argument n; creates a random n-by-n matrix;
     * solves the n-by-n assignment problem; and prints the optimal
     * solution.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {

        // create random n-by-n matrix
        int n = Integer.parseInt(args[0]);
        double[][] weight = new double[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                weight[i][j] = StdRandom.uniform(900) + 100;  // 3 digits
            }
        }

        // solve assignment problem
        AssignmentProblem assignment = new AssignmentProblem(weight);
        StdOut.printf("weight = %.0f\n", assignment.weight());
        StdOut.println();

        // print n-by-n matrix and optimal solution
        if (n >= 20) return;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (j == assignment.sol(i))
                    StdOut.printf("*%.0f ", weight[i][j]);
                else
                    StdOut.printf(" %.0f ", weight[i][j]);
            }
            StdOut.println();
        }
    }
示例#12
0
        public static void Main(string[] args)
        {
            // command-line arguments
            int N = int.Parse(args[0]);

            if (args.Length == 1)
            {
                // generate and print N numbers between 0.0 and 1.0
                for (int i = 0; i < N; i++)
                {
                    double x = StdRandom.Uniform();
                    Console.WriteLine(x);
                }
            }
            else if (args.Length == 3)
            {
                double lo = Double.Parse(args[1]);
                double hi = Double.Parse(args[2]);

                // generate and print N numbers between lo and hi
                for (int i = 0; i < N; i++)
                {
                    double x = StdRandom.Uniform(lo, hi);
                    Console.WriteLine("{0:N2}", x);
                }
            }
            else
            {
                throw new ArgumentException("Invalid number of arguments");
            }
        }
示例#13
0
    /**
     * Unit tests the {@code FloydWarshall} data type.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {

        // random graph with V vertices and E edges, parallel edges allowed
        int V = Integer.parseInt(args[0]);
        int E = Integer.parseInt(args[1]);
        AdjMatrixEdgeWeightedDigraph G = new AdjMatrixEdgeWeightedDigraph(V);
        for (int i = 0; i < E; i++) {
            int v = StdRandom.uniform(V);
            int w = StdRandom.uniform(V);
            double weight = Math.round(100 * (StdRandom.uniform() - 0.15)) / 100.0;
            if (v == w) G.addEdge(new DirectedEdge(v, w, Math.abs(weight)));
            else G.addEdge(new DirectedEdge(v, w, weight));
        }

        StdOut.println(G);

        // run Floyd-Warshall algorithm
        FloydWarshall spt = new FloydWarshall(G);

        // print all-pairs shortest path distances
        StdOut.printf("  ");
        for (int v = 0; v < G.V(); v++) {
            StdOut.printf("%6d ", v);
        }
        StdOut.println();
        for (int v = 0; v < G.V(); v++) {
            StdOut.printf("%3d: ", v);
            for (int w = 0; w < G.V(); w++) {
                if (spt.hasPath(v, w)) StdOut.printf("%6.2f ", spt.dist(v, w));
                else StdOut.printf("  Inf ");
            }
            StdOut.println();
        }

        // print negative cycle
        if (spt.hasNegativeCycle()) {
            StdOut.println("Negative cost cycle:");
            for (DirectedEdge e : spt.negativeCycle())
                StdOut.println(e);
            StdOut.println();
        }

        // print all-pairs shortest paths
        else {
            for (int v = 0; v < G.V(); v++) {
                for (int w = 0; w < G.V(); w++) {
                    if (spt.hasPath(v, w)) {
                        StdOut.printf("%d to %d (%5.2f)  ", v, w, spt.dist(v, w));
                        for (DirectedEdge e : spt.path(v, w))
                            StdOut.print(e + "  ");
                        StdOut.println();
                    }
                    else {
                        StdOut.printf("%d to %d no path\n", v, w);
                    }
                }
            }
        }

    }
示例#14
0
    /**
     * Returns a random rooted-out DAG on {@code V} vertices and {@code E} edges.
     * A rooted out-tree is a DAG in which every vertex is reachable from a
     * single vertex.
     * The DAG returned is not chosen uniformly at random among all such DAGs.
     * @param V the number of vertices
     * @param E the number of edges
     * @return a random rooted-out DAG on {@code V} vertices and {@code E} edges
     */
    public static Digraph rootedOutDAG(int V, int E) {
        if (E > (long) V*(V-1) / 2) throw new IllegalArgumentException("Too many edges");
        if (E < V-1)                throw new IllegalArgumentException("Too few edges");
        Digraph G = new Digraph(V);
        SET<Edge> set = new SET<Edge>();

        // fix a topological order
        int[] vertices = new int[V];
        for (int i = 0; i < V; i++)
            vertices[i] = i;
        StdRandom.shuffle(vertices);

        // one edge pointing from each vertex, other than the root = vertices[V-1]
        for (int v = 0; v < V-1; v++) {
            int w = StdRandom.uniform(v+1, V);
            Edge e = new Edge(w, v);
            set.add(e);
            G.addEdge(vertices[w], vertices[v]);
        }

        while (G.E() < E) {
            int v = StdRandom.uniform(V);
            int w = StdRandom.uniform(V);
            Edge e = new Edge(w, v);
            if ((v < w) && !set.contains(e)) {
                set.add(e);
                G.addEdge(vertices[w], vertices[v]);
            }
        }
        return G;
    }
示例#15
0
        public void Run()
        {
            const int n = 10;

            double[] t = { .5, .3, .1, .1 };
            Console.WriteLine("seed = {0}", StdRandom.GetSeed());
            for (var i = 0; i < n; i++)
            {
                Console.WriteLine("{0:D2}", StdRandom.Uniform(100));
                Console.WriteLine("{0:F3}", StdRandom.Uniform(10.0, 99.0));
                Console.WriteLine("{0}", StdRandom.Bernoulli(.5));
                Console.WriteLine("{0:F5}", StdRandom.Gaussian(9.0, .2));
                Console.WriteLine("{0:D2}", StdRandom.Discrete(t));
                Console.WriteLine();
            }

            var a = "A B C D E F G".Split(new [] { ' ' }).Cast <object>().ToArray();

            StdRandom.Shuffle(a);

            foreach (var s in a)
            {
                Console.WriteLine(s);
            }

            Console.ReadLine();
        }
示例#16
0
    /**
     * Unit tests the {@code Interval2D} data type.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {
        double xmin = Double.parseDouble(args[0]);
        double xmax = Double.parseDouble(args[1]);
        double ymin = Double.parseDouble(args[2]);
        double ymax = Double.parseDouble(args[3]);
        int trials = Integer.parseInt(args[4]);

        Interval1D xInterval = new Interval1D(xmin, xmax);
        Interval1D yInterval = new Interval1D(ymin, ymax);
        Interval2D box = new Interval2D(xInterval, yInterval);
        box.draw();

        Counter counter = new Counter("hits");
        for (int t = 0; t < trials; t++) {
            double x = StdRandom.uniform(0.0, 1.0);
            double y = StdRandom.uniform(0.0, 1.0);
            Point2D point = new Point2D(x, y);

            if (box.contains(point)) counter.increment();
            else                     point.draw();
        }

        StdOut.println(counter);
        StdOut.printf("box area = %.2f\n", box.area());
    }
示例#17
0
    /**
     * Unit tests the {@code Bipartite} data type.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {
        int V1 = Integer.parseInt(args[0]);
        int V2 = Integer.parseInt(args[1]);
        int E  = Integer.parseInt(args[2]);
        int F  = Integer.parseInt(args[3]);

        // create random bipartite graph with V1 vertices on left side,
        // V2 vertices on right side, and E edges; then add F random edges
        Graph G = GraphGenerator.bipartite(V1, V2, E);
        for (int i = 0; i < F; i++) {
            int v = StdRandom.uniform(V1 + V2);
            int w = StdRandom.uniform(V1 + V2);
            G.addEdge(v, w);
        }

        StdOut.println(G);


        Bipartite b = new Bipartite(G);
        if (b.isBipartite()) {
            StdOut.println("Graph is bipartite");
            for (int v = 0; v < G.V(); v++) {
                StdOut.println(v + ": " + b.color(v));
            }
        }
        else {
            StdOut.print("Graph has an odd-length cycle: ");
            for (int x : b.oddCycle()) {
                StdOut.print(x + " ");
            }
            StdOut.println();
        }
    }
示例#18
0
        /**/
        public static void main(string[] strarr)
        {
            int num = Integer.parseInt(strarr[0]);

            if (strarr.Length == 1)
            {
                for (int i = 0; i < num; i++)
                {
                    double d = StdRandom.uniform();
                    StdOut.println(d);
                }
            }
            else
            {
                if (strarr.Length != 3)
                {
                    string arg_87_0 = "Invalid number of arguments";

                    throw new ArgumentException(arg_87_0);
                }
                double d2 = java.lang.Double.parseDouble(strarr[1]);
                double d3 = java.lang.Double.parseDouble(strarr[2]);
                for (int j = 0; j < num; j++)
                {
                    double d4 = StdRandom.uniform(d2, d3);
                    StdOut.printf("%.2f\n", new object[]
                    {
                        java.lang.Double.valueOf(d4)
                    });
                }
            }
        }
示例#19
0
    /**
     * Reads in two command-line arguments lo and hi and prints n uniformly
     * random real numbers in [lo, hi) to standard output.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {

        // command-line arguments
        int n = Integer.parseInt(args[0]);

        // for backward compatibility with Intro to Programming in Java version of RandomSeq
        if (args.length == 1) {
            // generate and print n numbers between 0.0 and 1.0
            for (int i = 0; i < n; i++) {
                double x = StdRandom.uniform();
                StdOut.println(x);
            }
        }

        else if (args.length == 3) {
            double lo = Double.parseDouble(args[1]);
            double hi = Double.parseDouble(args[2]);

            // generate and print n numbers between lo and hi
            for (int i = 0; i < n; i++) {
                double x = StdRandom.uniform(lo, hi);
                StdOut.printf("%.2f\n", x);
            }
        }

        else {
            throw new IllegalArgumentException("Invalid number of arguments");
        }
    }
示例#20
0
        /// <summary>
        /// Returns a uniformly random tree on <tt>V</tt> vertices.
        /// This algorithm uses a Prufer sequence and takes time proportional to <em>V log V</em>.
        /// http://www.proofwiki.org/wiki/Labeled_Tree_from_Prüfer_Sequence
        /// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.36.6484&rep=rep1&type=pdf
        /// </summary>
        /// <param name="v">V the number of vertices in the tree</param>
        /// <returns>a uniformly random tree on <tt>V</tt> vertices</returns>
        public static Graph Tree(int v)
        {
            var g = new Graph(v);

            // special case
            if (v == 1)
            {
                return(g);
            }

            // Cayley's theorem: there are V^(V-2) labeled trees on V vertices
            // Prufer sequence: sequence of V-2 values between 0 and V-1
            // Prufer's proof of Cayley's theorem: Prufer sequences are in 1-1
            // with labeled trees on V vertices
            var prufer = new int[v - 2];

            for (var i = 0; i < v - 2; i++)
            {
                prufer[i] = StdRandom.Uniform(v);
            }

            // degree of vertex v = 1 + number of times it appers in Prufer sequence
            var degree = new int[v];

            for (var vi = 0; vi < v; vi++)
            {
                degree[vi] = 1;
            }
            for (var i = 0; i < v - 2; i++)
            {
                degree[prufer[i]]++;
            }

            // pq contains all vertices of degree 1
            var pq = new MinPQ <Integer>();

            for (var vi = 0; vi < v; vi++)
            {
                if (degree[vi] == 1)
                {
                    pq.Insert(vi);
                }
            }

            // repeatedly delMin() degree 1 vertex that has the minimum index
            for (var i = 0; i < v - 2; i++)
            {
                int vmin = pq.DelMin();
                g.AddEdge(vmin, prufer[i]);
                degree[vmin]--;
                degree[prufer[i]]--;
                if (degree[prufer[i]] == 1)
                {
                    pq.Insert(prufer[i]);
                }
            }
            g.AddEdge(pq.DelMin(), pq.DelMin());
            return(g);
        }
示例#21
0
        public void Run()
        {
            // create random DAG with V vertices and E edges; then add F random edges
            const int vv       = 50;
            const int e        = 100;
            const int f        = 20;
            var       digraph  = new EdgeWeightedDigraph(vv);
            var       vertices = new int[vv];

            for (var i = 0; i < vv; i++)
            {
                vertices[i] = i;
            }
            StdRandom.Shuffle(vertices);
            for (var i = 0; i < e; i++)
            {
                int v, w;
                do
                {
                    v = StdRandom.Uniform(vv);
                    w = StdRandom.Uniform(vv);
                } while (v >= w);
                var weight = StdRandom.Uniform();
                digraph.AddEdge(new DirectedEdge(v, w, weight));
            }

            // add F extra edges
            for (var i = 0; i < f; i++)
            {
                var v      = StdRandom.Uniform(vv);
                var w      = StdRandom.Uniform(vv);
                var weight = StdRandom.Uniform(0.0, 1.0);
                digraph.AddEdge(new DirectedEdge(v, w, weight));
            }

            Console.WriteLine(digraph);

            // find a directed cycle
            var finder = new EdgeWeightedDirectedCycle(digraph);

            if (finder.HasCycle())
            {
                Console.Write("Cycle: ");
                foreach (var edge in finder.Cycle())
                {
                    Console.Write(edge + " ");
                }
                Console.WriteLine();
            }

            // or give topologial sort
            else
            {
                Console.WriteLine("No directed cycle");
            }


            Console.ReadLine();
        }
示例#22
0
    /**
     * Unit tests the {@code TopologicalX} data type.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {

        // create random DAG with V vertices and E edges; then add F random edges
        int V = Integer.parseInt(args[0]);
        int E = Integer.parseInt(args[1]);
        int F = Integer.parseInt(args[2]);

        Digraph G1 = DigraphGenerator.dag(V, E);

        // corresponding edge-weighted digraph
        EdgeWeightedDigraph G2 = new EdgeWeightedDigraph(V);
        for (int v = 0; v < G1.V(); v++)
            for (int w : G1.adj(v))
                G2.addEdge(new DirectedEdge(v, w, 0.0));

        // add F extra edges
        for (int i = 0; i < F; i++) {
            int v = StdRandom.uniform(V);
            int w = StdRandom.uniform(V);
            G1.addEdge(v, w);
            G2.addEdge(new DirectedEdge(v, w, 0.0));
        }

        StdOut.println(G1);
        StdOut.println();
        StdOut.println(G2);

        // find a directed cycle
        TopologicalX topological1 = new TopologicalX(G1);
        if (!topological1.hasOrder()) {
            StdOut.println("Not a DAG");
        }

        // or give topologial sort
        else {
            StdOut.print("Topological order: ");
            for (int v : topological1.order()) {
                StdOut.print(v + " ");
            }
            StdOut.println();
        }

        // find a directed cycle
        TopologicalX topological2 = new TopologicalX(G2);
        if (!topological2.hasOrder()) {
            StdOut.println("Not a DAG");
        }

        // or give topologial sort
        else {
            StdOut.print("Topological order: ");
            for (int v : topological2.order()) {
                StdOut.print(v + " ");
            }
            StdOut.println();
        }
    }
示例#23
0
 /**
  * Initializes a particle with a random position and velocity.
  * The position is uniform in the unit box; the velocity in
  * either direciton is chosen uniformly at random.
  */
 public Particle() {
     rx     = StdRandom.uniform(0.0, 1.0);
     ry     = StdRandom.uniform(0.0, 1.0);
     vx     = StdRandom.uniform(-0.005, 0.005);
     vy     = StdRandom.uniform(-0.005, 0.005);
     radius = 0.02;
     mass   = 0.5;
     color  = Color.BLACK;
 }
示例#24
0
 /**
  * Returns the amount of time to call {@code ThreeSum.count()} with <em>n</em>
  * random 6-digit integers.
  * @param n the number of integers
  * @return amount of time (in seconds) to call {@code ThreeSum.count()}
  *   with <em>n</em> random 6-digit integers
  */
 public static double timeTrial(int n) {
     int[] a = new int[n];
     for (int i = 0; i < n; i++) {
         a[i] = StdRandom.uniform(-MAXIMUM_INTEGER, MAXIMUM_INTEGER);
     }
     Stopwatch timer = new Stopwatch();
     ThreeSum.count(a);
     return timer.elapsedTime();
 }
 public static void sort(string[] strarr)
 {
     StdRandom.shuffle(strarr);
     Quick3string.sort(strarr, 0, strarr.Length - 1, 0);
     if (!Quick3string.s_assertionsDisabled && !Quick3string.isSorted(strarr))
     {
         throw new AssertionError();
     }
 }
示例#26
0
 /**
  * Returns a random simple graph on {@code V} vertices, with an 
  * edge between any two vertices with probability {@code p}. This is sometimes
  * referred to as the Erdos-Renyi random graph model.
  * @param V the number of vertices
  * @param p the probability of choosing an edge
  * @return a random simple graph on {@code V} vertices, with an edge between
  *     any two vertices with probability {@code p}
  * @throws IllegalArgumentException if probability is not between 0 and 1
  */
 public static Graph simple(int V, double p) {
     if (p < 0.0 || p > 1.0)
         throw new IllegalArgumentException("Probability must be between 0 and 1");
     Graph G = new Graph(V);
     for (int v = 0; v < V; v++)
         for (int w = v+1; w < V; w++)
             if (StdRandom.bernoulli(p))
                 G.addEdge(v, w);
     return G;
 }
示例#27
0
        private static int[] CreateRandomArray(int n)
        {
            var a = new int[n];

            for (int i = 0; i < a.Length; i++)
            {
                a[i] = StdRandom.Uniform(10);
            }
            return(a);
        }
示例#28
0
 public static double Sample(StdRandom random, double mean = 0, double stdev = 0)
 {
     while (true)
     {
         if (PolarTransform(random.NextDouble(), random.NextDouble(), out var x, out var _))
         {
             return(mean + stdev * x);
         }
     }
 }
示例#29
0
 // tournament
 /**
  * Returns a random tournament digraph on {@code V} vertices. A tournament digraph
  * is a DAG in which for every two vertices, there is one directed edge.
  * A tournament is an oriented complete graph.
  * @param V the number of vertices
  * @return a random tournament digraph on {@code V} vertices
  */
 public static Digraph tournament(int V) {
     Digraph G = new Digraph(V);
     for (int v = 0; v < G.V(); v++) {
         for (int w = v+1; w < G.V(); w++) {
             if (StdRandom.bernoulli(0.5)) G.addEdge(v, w);
             else                          G.addEdge(w, v);
         }
     }
     return G;
 }
示例#30
0
 /**
  * Initializes a random flow network with {@code V} vertices and <em>E</em> edges.
  * The capacities are integers between 0 and 99 and the flow values are zero.
  * @param V the number of vertices
  * @param E the number of edges
  * @throws IllegalArgumentException if {@code V < 0}
  * @throws IllegalArgumentException if {@code E < 0}
  */
 public FlowNetwork(int V, int E) {
     this(V);
     if (E < 0) throw new IllegalArgumentException("Number of edges must be nonnegative");
     for (int i = 0; i < E; i++) {
         int v = StdRandom.uniform(V);
         int w = StdRandom.uniform(V);
         double capacity = StdRandom.uniform(100);
         addEdge(new FlowEdge(v, w, capacity));
     }
 }