测试代码:
var arr0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var ranNum0 = 5;
console.log(getDiffArr(arr0, ranNum0));
方法实现:
1. 不断缩减原数组,一次抽一个
function getDiffArr(arr, num) { var arrOut = []; for (var i = 0; i < num; i++) { var ran = Math.floor(Math.random() * arr.length); arrOut.push(arr[ran]); arr = (function (arr, ran) { var arrOut = []; for (var m = 0, n = arr.length; m < n; m++) { if (arr[m] != arr[ran]) { arrOut.push(arr[m]); } } return arrOut; }(arr, ran)); } return arrOut; }
2.从抽第二个起,新数组元素遍历比较当前随机元素,若抽到相同的则重抽
function getDiffArr(arr, num) { var arrOut = []; var ran; for (var i = 0; i < num; i++) { ran = Math.floor(Math.random() * arr.length); // arrOut.push(arr[ran]); // error arrOut[i]=arr[ran]; if (i > 0) { for (var m = 0; m < i; m++) { if (arrOut[m] == arr[ran]) { i--; break; } } } } return arrOut; }
2.1 利用 flag 判定是否全不等
var arr = [1, 2, 3, 4, 5, 6, 7, 8] function getDif(arr, num) { var arrOut = []; while (num > 0) { var ran = Math.floor(Math.random() * arr.length); num--; if (arrOut.length > 0) { var flag=false; for (var i = 0; i < arrOut.length; i++) { if (arrOut[i] == arr[ran]) { num++; flag=true; break; } } if(!flag){ arrOut.push(arr[ran]); } }else{ arrOut.push(arr[ran]); } } return arrOut; } console.log(getDif(arr, 5));
3.利用对象属性唯一性与数组形成绑定关系
function getDiffArr(arr,num) { var hash = {}; var arrOut = []; while (num > 0) { var ran = Math.floor(Math.random() * arr.length); if (!hash[ran]) { hash[ran] = 1; arrOut.push(ran); num--; }; } return arrOut; }
3.1 不同的循环方式
var arr = [1, 2, 3, 4, 5, 6, 7, 8] function getDif(arr, num) { var arrOut = []; var hash = {}; var len = arr.length; while(num){ var ran = Math.floor(Math.random() * len); if(!hash[ran]){ arrOut.push(arr[ran]); hash[ran] = 1; num--; } } // for (var i = 0; i < num; i++) { // var ran = Math.floor(Math.random() * len); // if (!hash[ran]) { // arrOut.push(arr[ran]); // hash[ran] = 1; // }else{ // num++; // } // } return arrOut; } console.log(getDif(arr, 5));
4. 不断缩减数组长度,减少比较次数和排除抽取重复元素的可能
var arr = [1, 2, 3, 4, 5, 6, 7, 8] function getDif(arr, num) { var arrOut = []; for (var i = 0; i < num; i++) { var len=arr.length; var ran = Math.floor(Math.random() * len); arrOut[i] = arr[ran]; arr[ran]=arr[len-1]; arr.pop(); // arr=arr.slice(0,arr.length-1);
} return arrOut; } console.log(getDif(arr, 5));
4.1 优化算法:规避数组长度操作
var arr = [1, 2, 3, 4, 5, 6, 7, 8]; function getDif(arr, num) { var arrOut = []; var len=arr.length; for (var i = 0; i < num; i++) { var ran = Math.floor(Math.random() * (len-i)); arrOut[i] = arr[ran]; arr[ran]=arr[len-i-1]; } return arrOut; } console.log(getDif(arr, 5));
4.2 抽一个删一个
var arr = [1, 2, 3, 4, 5, 6, 7, 8]; function getDif(arr, num) { var arrOut = []; for (var i = 0; i < num; i++) { var len = arr.length; var ran = Math.floor(Math.random() * len); arrOut[i] = arr.splice(ran, 1)[0]; } return arrOut; } console.log(getDif(arr, 5));