javascript - One array taking random elements from another array
PHP中文网2017-05-19 10:31:39
0
7
739
There is an array a=[4,19,23,44,56,1], create a new array b, and b randomly selects one element at a time from a until it is exhausted. Implemented in JavaScript
You can shuffle a with pseudo-randomness, exchange the numbers in any two positions, do this n times to achieve the shuffling effect, and then assign it to b.
Or just follow the steps. If code efficiency is not considered, the array operations provided by the lodash library can make the code more elegant:
var src = [4,19,23,44,56,1];
var shuffle = [];
while(src.length > 0){
var random_index = Math.floor(Math.random() * src.length);
shuffle.push(src[random_index]);
src = src.filter(function(el, i){
return i != random_index;
});
}
I thought of a better pseudorandom method, which is directly sorted randomly, the code is simpler, and the operation efficiency is high:
var src = [4,19,23,44,56,1];
var shuffle = src;
shuffle.sort(function(){
return Math.floor(Math.random() * 3) - 1;
});
var a=[4,19,23,44,56,1];
var b=[];
var c=[0,0,0,0,0,0];
var aLen = a.length;
while (c.indexOf(0)!=-1){
var randomNum = Math.floor(Math.random()*aLen);
if (c[randomNum] == 0){
b.push(a[randomNum]);
c[randomNum]=1
}
}
console.log(b);
var a=[4,19,23,44,56,1];
function randomSelect(str){
var leng= a.length;
var b=[];
while(leng!=0){
b.push(a.splice(Math.random()*leng,1).join())
leng--;
}
return b;
}
console.log(randomSelect(a));
I won’t write it down to the fourth floor. I just randomly select one from the array one at a time. After randomization, remove it from the array. Continue randomizing. Just push the removed ones into the new array and it will be ok
You can shuffle a with pseudo-randomness, exchange the numbers in any two positions, do this n times to achieve the shuffling effect, and then assign it to b.
Or just follow the steps. If code efficiency is not considered, the array operations provided by the lodash library can make the code more elegant:
I thought of a better
pseudorandom method, which is directly sorted randomly, the code is simpler, and the operation efficiency is high:The implementation is as follows:
My idea is to traverse this array, get random elements in this array, delete them from array a and push them into array b, and so on
I won’t write it down to the fourth floor. I just randomly select one from the array one at a time. After randomization, remove it from the array. Continue randomizing. Just push the removed ones into the new array and it will be ok