Picking 2 random elements from array

前端 未结 9 946
一向
一向 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

    http://underscorejs.org/#sample

    _.sample(list, [n])

    Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.

    _.sample([1, 2, 3, 4, 5, 6]);
    => 4
    
    _.sample([1, 2, 3, 4, 5, 6], 3);
    => [1, 6, 2]
    

    Looking at the source it uses shuffle just like @thg435 suggested.

提交回复
热议问题