• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java StdRandom类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: erdosRenyiGraphGaussianWeights

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
public Exercise28_SpaceEfficientDataStructures.EdgeWeightedGraphSpaceEfficient erdosRenyiGraphGaussianWeights(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 gaussianRandomWeight = StdRandom.gaussian();
        Edge newEdge = new Edge(vertexId1, vertexId2, gaussianRandomWeight);

        randomEdgeWeightedGraphSpaceEfficient.addEdge(newEdge);
    }

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


示例17: timeRandomInput

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
private static double timeRandomInput(SortTypes sortType, int initialLength, int numberOfExperiments) {
    double total = 0;
    int length = initialLength;

    for(int experiment = 0; experiment < numberOfExperiments; experiment++) {
        Comparable[] array = new Comparable[length];

        for(int i=0; i < length; i++) {
            array[i] = StdRandom.uniform();
        }

        total += time(sortType, array);

        length *= 2;
    }

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


示例18: getRandomCoordinates

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
private Coordinate[] getRandomCoordinates(EdgeWeightedGraph edgeWeightedGraph) {
            Coordinate[] vertexCoordinates = new Coordinate[edgeWeightedGraph.vertices()];

            for(int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {
                // tinyEWG coordinates
//                double randomXCoordinate = StdRandom.uniform();
//                double randomYCoordinate = StdRandom.uniform();

                double randomXCoordinate = StdRandom.uniform(1000);
                double randomYCoordinate = StdRandom.uniform(1000);

                vertexCoordinates[vertex] = new Coordinate(randomXCoordinate, randomYCoordinate);
            }

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


示例19: connectVerticesToNeighbors

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
private void connectVerticesToNeighbors(Exercise30_EuclideanWeightedGraphs.EuclideanEdgeWeightedGraph randomEuclideanGridEdgeWeightedGraph,
                                        int vertexNumberSqrt) {
    int[] neighborRows = {-1, 1, 0 ,0};
    int[] neighborColumns = {0, 0, -1 ,1};

    for(int row = 0; row < vertexNumberSqrt; row++) {
        for(int column = 0; column < vertexNumberSqrt; column++) {
            for(int i = 0; i < 4; i++) {
                int neighborRow = row + neighborRows[i];
                int neighborColumn = column + neighborColumns[i];

                if(isValidCell(vertexNumberSqrt, neighborRow, neighborColumn)) {
                    int vertexId1 = getVertexId(row, column, vertexNumberSqrt);
                    int vertexId2 = getVertexId(neighborRow, neighborColumn, vertexNumberSqrt);

                    //Used to avoid connecting vertices more than once
                    if(vertexId1 < vertexId2) {
                        double randomEdgeWeight = StdRandom.uniform();
                        Edge edge = new Edge(vertexId1, vertexId2, randomEdgeWeight);
                        randomEuclideanGridEdgeWeightedGraph.addEdge(edge);
                    }
                }
            }
        }
    }
}
 
开发者ID:reneargento,项目名称:algorithms-sedgewick-wayne,代码行数:27,代码来源:Exercise36_RandomGridEdgeWeightedGraphs.java


示例20: generate95PercentSortedArray

import edu.princeton.cs.algs4.StdRandom; //导入依赖的package包/类
private static Comparable[] generate95PercentSortedArray(int arrayLength) {

        Comparable[] array = new Comparable[arrayLength];

        int fivePercentLength = (int) (arrayLength * 0.05);

        for(int i=0; i < arrayLength; i++) {
            array[i] = i;
        }

        //Shuffle 5% of values
        for(int i=0; i <= fivePercentLength / 2; i++) {
            int randomIndex1 = StdRandom.uniform(0, arrayLength);
            int randomIndex2 = StdRandom.uniform(0, arrayLength);

            Comparable temp = array[randomIndex1];
            array[randomIndex1] = array[randomIndex2];
            array[randomIndex2] = temp;
        }

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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java Artwork类代码示例发布时间:2022-05-22
下一篇:
Java SerializationUtils类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap