Picking 2 random elements from array

前端 未结 9 933
一向
一向 2020-12-16 18:32

What is the most efficient way to select 2 unique random elements from an array (ie, make sure the same element is not selected twice).

I have so far:



        
9条回答
  •  伪装坚强ぢ
    2020-12-16 19:18

    If you shuffle the array and splice the number of elements you want to return, the return value will contain as many items as it can, if you ask for more items than are in the array. You can shuffle the actual array or a copy, with slice().

    Array.prototype.getRandom= function(num, cut){
        var A= cut? this:this.slice(0);
        A.sort(function(){
            return .5-Math.random();
        });
        return A.splice(0, num);
    }
    var a1= [1, 2, 3, 4, 5];
    a1.getRandom(2)
    >>[4, 2]
    

    If you want to remove the selected items from the original array, so that a second call will not include the elements the first call returned, pass a second argument: getRandom(3,true);

    window.Memry=window.Memry || {};
    Memry.a1= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    Memry.a1.getRandom(3,true);
    >>[5,10,7]
    Memry.a1.getRandom(3,true);
    >>[3,9,6]
    Memry.a1.getRandom(3,true);
    >>[8,4,1]
    Memry.a1.getRandom(3,true);
    >>[2]
    

提交回复
热议问题