Picking 2 random elements from array

前端 未结 9 952
一向
一向 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:27

    While shuffle the array and pick the first two is correct.
    You don't need to shuffle the whole array.

    Just shuffle the first two!

    var arrElm = [1, 2, 3, 4, 5, 6, 7]
    
    var toTake = 2
    
    var maxToShuffle = Math.min(arrElm.length - 1, toTake)
    
    for (let i = 0; i < maxToShuffle; i++) {
      const toSwap = i + Math.floor(Math.random() * (arrElm.length - i))
      ;[arrElm[i], arrElm[toSwap]] = [arrElm[toSwap], arrElm[i]]
    }
    
    console.log(arrElm.slice(0, toTake))
    

    basically the same as https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

    Except you just quit early when you have enough item shuffled.

提交回复
热议问题