• Floyd提出的随机数产生方法


    要产生M个0-N的不同的随机数,方案?
    1:将产生的随机数放入到集合中,产生一个随机数判断是否在集合中,不在的话放入,知道集合为M为止
    2:
    Algorithm F2
    init set S to empty
    size = 0
    for j = n - m + 1 to n
    t = random(1,j)
    if t is not in S then
    insert t to S
    else
    insert j to S
    算法实现如下:
    package test;

    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Random;

    public class Odd {
    public static void main(String[] args) {
    //System.out.println((-5)%2);
    random(50,100);
    randomFloyd(50,100);
    }
    //Floyd的算法
    static void randomFloyd(int m,int n)
    {
    int index=0;
    Random r=new Random();
    HashSet<integer> hs=new HashSet<integer>();
    for (int i = n-m+1; i &lt;=n; i++) {
    int k=r.nextInt(i);
    if(!hs.contains(k))
    hs.add(k);
    else
    hs.add(i);
    index++;
    }
    System.out.println("运行"+index+"次");
    System.out.println(Arrays.toString(hs.toArray()));
    System.out.println(hs.size());
    }
    //算法1
    static void random(int m,int n){
    int index=0;
    Random r=new Random();
    HashSet<integer> hs=new HashSet<integer>();
    while (hs.size()!=m) {
    int k=r.nextInt(n);
    if(!hs.contains(k))
    hs.add(k);
    index++;
    }
    System.out.println("运行"+index+"次");
    System.out.println(Arrays.toString(hs.toArray()));
    }
    }
    运行结果:
    运行68次
    [0, 5, 8, 10, 12, 14, 15, 19, 18, 20, 23, 25, 28, 31, 30, 33, 39, 36, 37, 42, 46, 47, 44, 51, 54, 52, 57, 63, 62, 68, 69, 70, 71, 64, 65, 76, 72, 74, 75, 84, 87, 86, 81, 82, 92, 94, 88, 91, 90, 98]
    运行50次
    [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 15, 17, 16, 18, 21, 25, 29, 28, 31, 30, 32, 33, 36, 42, 50, 49, 48, 53, 59, 62, 61, 60, 69, 70, 64, 67, 78, 79, 74, 86, 80, 83, 82, 93, 92, 94, 91, 90, 97]
  • 相关阅读:
    UDS 诊断协议 $36
    UDS 诊断协议 $34
    RH850 CS+工程 定义常量变量到指定ROM地址
    关于ARM 架构汇编指令
    RH850 FDL的使用
    robotframework Selenium2+RFS自动化测试
    虫师 博客园 http://www.cnblogs.com/fnng/
    Excel数据比对-批量数据比对
    web自动化测试 Selenium2 Java自动化测试实战9_3
    loadrunner11 +Win7 + 支持ie9,录制成功
  • 原文地址:https://www.cnblogs.com/macula7/p/1960442.html
Copyright © 2020-2023  润新知