// 洗牌算法
var a = [1,2,3,4,5,6,7,8,9];
//方法1
function randomList(arr){
var newArr = [];
while(arr.length > 0){
//从现有的数组中随机找一个放入新数组中
var random = Math.floor(Math.random() * arr.length);
newArr.push(arr[random]);
arr.splice(random,1);
}
return newArr;
}
var b = randomList(a);
console.log(b);
var c = [1,2,3,4,5,6,7,8,9];
//方法2
function randomList2(arr){
for(let i = arr.length - 1 ; i > 0; i--){
//随机一个与i交换位置
var random = Math.floor(Math.random() * arr.length);
var temp = arr[random];
arr[random] = arr[i];
arr[i] = temp;
}
}
randomList2(c)
console.log(c)
随机打算数组【洗牌算法】
最新推荐文章于 2023-10-05 19:24:34 发布