關於Math.random() 隨機數 與 洗牌演算法
阿新 • • 發佈:2020-10-10
// 手寫可控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());