算法前置知识02-随机函数

一、Math.random()

概率P(Math.random()<0.3) = 0.3

若x∈(0,1) 则x²概率表达为

Math.min(Math.random()<x,Math.random()<x)

二、等概率转换

给出一个黑盒f()等概率返回1、2、3、4、5,根据f()写一个等概率返回123456的函数

    //等概率返回0,1的函数
    public static int f1() {
        int res = -1;
        do {
            res = f();
        } while (res == 3);
        return res < 3 ? 0 : 1;
    }

    //等概率返回0-7
    public static int f2() {
        return (f1() << 2) + (f1() << 1) + f1();
    }

    //等概率返回1-6
    public static int f3() {
        int res = -1;
        do {
            res = f2();
        } while (res == 0 || res == 7);
        return res;
    }

三、不等概率转换

给出一个黑盒f()不等概率返回0,1,根据f()写一个等概率返回0,1的函数

public static int f1(){
        int res = -1;
        do {
            res = f();
        }while (res == f());
        return res;
    }

四、生成一个随机数组

public static int[] randomArr(int maxLen, int maxValue) {
        int len = (int) (Math.random() * maxLen);
        int[] arr = new int[len];
        for (int i = 0; i < len; i++) {
            arr[i] = (int) (Math.random() * maxValue);
        }
        return arr;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值