当前位置: 首页>>代码示例>>Java>>正文


Java StdRandom类代码示例

本文整理汇总了Java中edu.princeton.cs.algs4.StdRandom的典型用法代码示例。如果您正苦于以下问题:Java StdRandom类的具体用法?Java StdRandom怎么用?Java StdRandom使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


StdRandom类属于edu.princeton.cs.algs4包,在下文中一共展示了StdRandom类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: farthestPair

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
/**
 * Ex 1.4.17
 * Farthest Pair
 * O(N)
 * @param n
 *		数组的元素个数
 */
private static void farthestPair(int n) {
    //创建并打乱数组
    double[] a = new double[n];

    for (int i = 0; i < n; i++)
        a[i] = i;

    StdRandom.shuffle(a);

    double min = a[0];
    double max = a[0];

    for (int i = 0; i < n; i++) {
        //找出最小的数
        min = Math.min(a[i], min);
        max = Math.max(a[i], max);
    }

    o("相差最大的两个数分别是: " + min + ", "+ max);

}
 
开发者ID:DCMMC,项目名称:Java-Algorithms-Learning,代码行数:29,代码来源:AnalysisOfAlgorithms.java

示例2: sample

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
/**
* return (but do not remove) a random item
*/
public Item sample() {
	if (size() == 0)
		throw new NoSuchElementException("");

	//generate the random index that will be dequeued.
	int outIndex = StdRandom.uniform(size);

	Node tmp = last;
	Node tmpNext = null;

	for (int i = 0; i < outIndex; i++) {
		tmpNext = tmp;
		tmp = tmp.previous;
	}

	return tmp.item;
}
 
开发者ID:DCMMC,项目名称:Java-Algorithms-Learning,代码行数:21,代码来源:RandomizedQueue.java

示例3: PercolationStats

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
/**
* perform trials independent experiments on an n-by-n grid
* @param n
*          grid的大小
* @param trials
*          尝试trials次试验
*/
public PercolationStats(int n, int trials) {
    //检验参数合法性
    if (n <= 0 || trials <= 0)
        throw new IllegalArgumentException("参数不能小于等于0!");

    results = new double[trials];

    for(int i = 0;i < trials;i++) {
        Percolation percolationTest = new Percolation(n);

        int rndRow, rndCol;
        while (!percolationTest.percolates()) {
            if(percolationTest.isOpen(rndRow = (StdRandom.uniform(n) + 1), rndCol = (StdRandom.uniform(n) + 1)))
                continue;
            else
                percolationTest.open(rndRow, rndCol);
        }
        results[i] = (percolationTest.numberOfOpenSites() * 1.0) / (n * n);
    }

    mean = StdStats.mean(results);
    stddev = StdStats.stddev(results);
}
 
开发者ID:DCMMC,项目名称:Java-Algorithms-Learning,代码行数:31,代码来源:PercolationStats.java

示例4: quickSortWithSentinels

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
/**
* Ex 2.3.17
* Sentinels
* 使用哨兵减少冗余的if判断
* @param a
*       要排序的数组
*/
@SuppressWarnings("unchecked")
private static void quickSortWithSentinels(Comparable[] a) {
    //把a打乱
    StdRandom.shuffle(a);

    //找到最大的item并且交换到a[length - 1]
    //sentinel2
    int indexOfMax = 0;
    for (int i = 1; i < a.length; i++)
        if (a[i].compareTo(a[indexOfMax]) > 0)
            indexOfMax = i;
    exch(a, indexOfMax, a.length - 1);

    quickSortWithSentinels(a, 0, a.length - 1);
}
 
开发者ID:DCMMC,项目名称:Java-Algorithms-Learning,代码行数:23,代码来源:QuicksortEx.java

示例5: PercolationStats

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
public PercolationStats(int n, int trials) {
    if (n <= 0 || trials <= 0) throw new IllegalArgumentException();

    results = new double[trials];

    for (int i = 0; i < trials; i++) {
        Percolation percolation = new Percolation(n);
        while (!percolation.percolates()) {
            int row = StdRandom.uniform(1, n + 1);
            int col = StdRandom.uniform(1, n + 1);
            if (!percolation.isOpen(row, col)) percolation.open(row, col);
        }

        int openSites = percolation.numberOfOpenSites();
        results[i] = (double) openSites / (double) (n * n);

    }

    mean = StdStats.mean(results);
    stddev = StdStats.stddev(results);
}
 
开发者ID:SkullTech,项目名称:algorithms-princeton,代码行数:22,代码来源:PercolationStats.java

示例6: main

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
public static void main(String[] args) {
    Exercise20_DynamicGrowth dynamicGrowth = new Exercise20_DynamicGrowth();

    DynamicWeightedQuickUnion dynamicWeightedQuickUnion = dynamicGrowth.new DynamicWeightedQuickUnion();

    //Add five sites
    dynamicWeightedQuickUnion.newSite();
    dynamicWeightedQuickUnion.newSite();
    dynamicWeightedQuickUnion.newSite();
    dynamicWeightedQuickUnion.newSite();
    dynamicWeightedQuickUnion.newSite();


    while(dynamicWeightedQuickUnion.count() != 1) {

        int randomSite1 = StdRandom.uniform(dynamicWeightedQuickUnion.getNumberOfSites());
        int randomSite2 = StdRandom.uniform(dynamicWeightedQuickUnion.getNumberOfSites());

        if(!dynamicWeightedQuickUnion.connected(randomSite1, randomSite2)) {
            dynamicWeightedQuickUnion.union(randomSite1, randomSite2);

            StdOut.println("United sites " + randomSite1 + " and " + randomSite2);
        }
    }
}
 
开发者ID:reneargento,项目名称:algorithms-sedgewick-wayne,代码行数:26,代码来源:Exercise20_DynamicGrowth.java

示例7: simple

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
/**
 * Returns a random simple graph containing <tt>V</tt> vertices and <tt>E</tt> edges.
 * @param V the number of vertices
 * @param E the number of vertices
 * @return a random simple graph on <tt>V</tt> vertices, containing a total
 *     of <tt>E</tt> edges
 * @throws IllegalArgumentException if no such simple graph exists
 */
public static Graph simple(int V, int E) {
    if (E > (long) V*(V-1)/2) throw new IllegalArgumentException("Too many edges");
    if (E < 0)                throw new IllegalArgumentException("Too few edges");
    Graph G = new Graph(V);
    SET<Edge> set = new SET<Edge>();
    while (G.E() < E) {
        int v = StdRandom.uniform(V);
        int w = StdRandom.uniform(V);
        Edge e = new Edge(v, w);
        if ((v != w) && !set.contains(e)) {
            set.add(e);
            G.addEdge(v, w);
        }
    }
    return G;
}
 
开发者ID:yunfeiguo,项目名称:bioinfo_toolbox,代码行数:25,代码来源:GraphGenerator.java

示例8: generateRandomTransactions

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
private Exercise21_ComparableTransactions[] generateRandomTransactions(int numberOfObjects) {
    Exercise21_ComparableTransactions[] transactions = new Exercise21_ComparableTransactions[numberOfObjects];

    for(int i=0; i < numberOfObjects; i++) {
        String who = "Client " + (i + 1);

        int month = StdRandom.uniform(12) + 1;
        int maxDay = month == 2 ? 28 : 30;
        int day = StdRandom.uniform(maxDay) + 1;
        int year = StdRandom.uniform(1900, 2018);
        Date date = new Date(month, day, year);

        double amount = (double) Math.round(StdRandom.uniform(0.0, 1000000.0) * 100) / 100;

        Exercise21_ComparableTransactions transaction = new Exercise21_ComparableTransactions(who, date, amount);
        transactions[i] = transaction;
    }

    return transactions;
}
 
开发者ID:reneargento,项目名称:algorithms-sedgewick-wayne,代码行数:21,代码来源:Exercise33_RandomTransactions.java

示例9: eulerianCycle

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
/**
 * Returns an Eulerian cycle graph on <tt>V</tt> vertices.
 *
 * @param  V the number of vertices in the cycle
 * @param  E the number of edges in the cycle
 * @return a graph that is an Eulerian cycle on <tt>V</tt> vertices
 *         and <tt>E</tt> edges
 * @throws IllegalArgumentException if either V &le; 0 or E &le; 0
 */
public static Graph eulerianCycle(int V, int E) {
    if (E <= 0)
        throw new IllegalArgumentException("An Eulerian cycle must have at least one edge");
    if (V <= 0)
        throw new IllegalArgumentException("An Eulerian cycle must have at least one vertex");
    Graph G = new Graph(V);
    int[] vertices = new int[E];
    for (int i = 0; i < E; i++)
        vertices[i] = StdRandom.uniform(V);
    for (int i = 0; i < E-1; i++) {
        G.addEdge(vertices[i], vertices[i+1]);
    }
    G.addEdge(vertices[E-1], vertices[0]);
    return G;
}
 
开发者ID:yunfeiguo,项目名称:bioinfo_toolbox,代码行数:25,代码来源:GraphGenerator.java

示例10: wheel

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
/**
 * Returns a wheel graph on <tt>V</tt> vertices.
 * @param V the number of vertices in the wheel
 * @return a wheel graph on <tt>V</tt> vertices: a single vertex connected to
 *     every vertex in a cycle on <tt>V-1</tt> vertices
 */
public static Graph wheel(int V) {
    if (V <= 1) throw new IllegalArgumentException("Number of vertices must be at least 2");
    Graph G = new Graph(V);
    int[] vertices = new int[V];
    for (int i = 0; i < V; i++)
        vertices[i] = i;
    StdRandom.shuffle(vertices);

    // simple cycle on V-1 vertices
    for (int 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 (int i = 1; i < V; i++) {
        G.addEdge(vertices[0], vertices[i]);
    }

    return G;
}
 
开发者ID:yunfeiguo,项目名称:bioinfo_toolbox,代码行数:28,代码来源:GraphGenerator.java

示例11: insertsAndRemovesIn1Second

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
private static int insertsAndRemovesIn1Second(PriorityQueue<Double> priorityQueue, Comparable[] keys) {
    //Fill the priority queue
    for(int i=0; i < keys.length; i++) {
        priorityQueue.insert((double) keys[i]);
    }

    int numberOfRemoveMaxIn1Second = 0;
    int randomIndex = StdRandom.uniform(keys.length);

    Stopwatch timer = new Stopwatch();
    while (timer.elapsedTime() <= 1) {
        priorityQueue.deleteTop();
        numberOfRemoveMaxIn1Second++;
        priorityQueue.insert((double) keys[randomIndex]);
    }

    return numberOfRemoveMaxIn1Second;
}
 
开发者ID:reneargento,项目名称:algorithms-sedgewick-wayne,代码行数:19,代码来源:Exercise37_PerformanceDriverII.java

示例12: regular

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
/**
 * 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.
 * @param V the number of vertices in the graph
 * @return a uniformly random <tt>k</tt>-regular graph on <tt>V</tt> vertices.
 */
public static Graph regular(int V, int k) {
    if (V*k % 2 != 0) throw new IllegalArgumentException("Number of vertices * k must be even");
    Graph G = new Graph(V);

    // create k copies of each vertex
    int[] vertices = new int[V*k];
    for (int v = 0; v < V; v++) {
        for (int j = 0; j < k; j++) {
            vertices[v + V*j] = v;
        }
    }

    // pick a random perfect matching
    StdRandom.shuffle(vertices);
    for (int i = 0; i < V*k/2; i++) {
        G.addEdge(vertices[2*i], vertices[2*i + 1]);
    }
    return G;
}
 
开发者ID:yunfeiguo,项目名称:bioinfo_toolbox,代码行数:27,代码来源:GraphGenerator.java

示例13: erdosRenyiGeneratingConnections

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
private List<Exercise18_RandomGridGenerator.Connection> erdosRenyiGeneratingConnections(int numberOfSites, UF unionFind) {

        List<Exercise18_RandomGridGenerator.Connection> connectionsGenerated = new ArrayList<>();

        while(unionFind.count() != 1) {

            int randomSite1 = StdRandom.uniform(numberOfSites);
            int randomSite2 = StdRandom.uniform(numberOfSites);

            Exercise18_RandomGridGenerator.Connection connection = new Exercise18_RandomGridGenerator().new Connection(
                    randomSite1, randomSite2);
            connectionsGenerated.add(connection);

            if(!unionFind.connected(randomSite1, randomSite2)) {
                unionFind.union(randomSite1, randomSite2);
            }
        }

        return connectionsGenerated;
    }
 
开发者ID:reneargento,项目名称:algorithms-sedgewick-wayne,代码行数:21,代码来源:Exercise24_FastAlgorithmsErdosRenyi.java

示例14: generateWorstCaseGraphForEagerPrim

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
public EdgeWeightedGraphWithNeighborsInOrder generateWorstCaseGraphForEagerPrim(int vertices) {
    EdgeWeightedGraphWithNeighborsInOrder edgeWeightedGraph = new EdgeWeightedGraphWithNeighborsInOrder(vertices);

    double maxWeight = StdRandom.uniform();
    double valueToDecrease = 0.00001;

    for(int vertex1 = 0; vertex1 < vertices; vertex1++) {
        valueToDecrease = valueToDecrease + 0.00001;

        for(int vertex2 = vertex1 + 1; vertex2 < vertices; vertex2++) {
            double weight = maxWeight - valueToDecrease;
            Edge edge = new Edge(vertex1, vertex2, weight);
            edgeWeightedGraph.addEdge(edge);
        }
    }

    return edgeWeightedGraph;
}
 
开发者ID:reneargento,项目名称:algorithms-sedgewick-wayne,代码行数:19,代码来源:Exercise25_WorstCaseGenerator.java

示例15: erdosRenyiGraphUniformWeights

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
public Exercise28_SpaceEfficientDataStructures.EdgeWeightedGraphSpaceEfficient erdosRenyiGraphUniformWeights(int vertices,
                                                                                                             int edges) {
    Exercise28_SpaceEfficientDataStructures.EdgeWeightedGraphSpaceEfficient randomEdgeWeightedGraphSpaceEfficient =
            spaceEfficientDataStructures.new EdgeWeightedGraphSpaceEfficient(vertices);

    for(int edge = 0; edge < edges; edge++) {
        int vertexId1 = StdRandom.uniform(vertices);
        int vertexId2 = StdRandom.uniform(vertices);

        double uniformRandomWeight = StdRandom.uniform();
        Edge newEdge = new Edge(vertexId1, vertexId2, uniformRandomWeight);

        randomEdgeWeightedGraphSpaceEfficient.addEdge(newEdge);
    }

    return randomEdgeWeightedGraphSpaceEfficient;
}
 
开发者ID:reneargento,项目名称:algorithms-sedgewick-wayne,代码行数:18,代码来源:Exercise40_ReducedOverhead.java


注:本文中的edu.princeton.cs.algs4.StdRandom类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。