zoukankan      html  css  js  c++  java
  • JS封装 随机数

    // 手写可控rendom()函数
    let seed = new Date();
    function random(){
        let x = Math.sin(seed++) * 10000;
        return x - Math.floor(x);
    }
    console.log(random());
    // 洗牌算法
    let arr = [1, 2, 3, 4, 5, 6];
    function shuffle(arr){
        for(let i = arr.length - 1; i >= 0; i--){
            let randomIndex = Math.floor(Math.random() * (i + 1));
            let itemAtIndex = arr[randomIndex];
            arr[randomIndex] = arr[i];
            arr[i] = itemAtIndex;
        }
        return arr;
    }
    console.log(shuffle(arr));
    // 洗牌算法 - 数组原型方法
    Array.prototype.shufflePro = function () {
        let input = this;
        for (let i = input.length - 1; i >= 0; i--) {
            // let randomIndex = Math.floor(Math.random() * (i + 1));
            let randomIndex = Math.floor(Math.random() * input.length);
            let itemAtIndex = input[randomIndex];
            input[randomIndex] = input[i];
            input[i] = itemAtIndex;
        }
        return input;
    }
    let tempArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
    console.log(tempArray.shufflePro());
    // 加密随机数1
    function luckyNum(n = 1){
        let array = new Uint32Array(n);
        let luckyArr = [];
        window.crypto.getRandomValues(array);
        for (var i = 0; i < array.length; i++) {
            luckyArr.push(array[i]);
        }
        console.log(n);
        return luckyArr;
    }
    console.log(luckyNum());
    // 加密随机数2
    function luckyNum(n = 1, m = 2){   
        console.log(n);
        let array = new Uint32Array(n);
        let luckyArr = [];
        window.crypto.getRandomValues(array);
        for (var i = 0; i < array.length; i++) {
            luckyArr.push(array[i].toString().slice(0, m)*1);
        }
        return luckyArr;
    }
    console.log(luckyNum());
  • 相关阅读:
    27. Remove Element
    列表变成字典
    1. Two Sum
    CVPR2019:What and How Well You Performed? A Multitask Learning Approach to Action Quality Assessment
    959. Regions Cut By Slashes
    118. Pascal's Triangle
    loj3117 IOI2017 接线 wiring 题解
    题解 NOI2019 序列
    题解 省选联考2020 组合数问题
    题解 Educational Codeforces Round 90 (Rated for Div. 2) (CF1373)
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/13790454.html
Copyright © 2011-2022 走看看