# Select random poker without duplicates

如何拿不重覆 array

13 張撲克牌 ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'],隨機抽兩張

怎麼解

訣竅在於先把這 Array 隨機打散,再來看你要拿幾張都可以


const ram = (N) => Math.floor(Math.random() * N);

/**
 * @param {string[]} pokers
 * @param {number} count 取多少個
 * @return {string[]}
 */
 
function randomPoker (pokers, count) {
  let randomPokers = [];
  
  for(; count > 0 ; count--){
    let len = pokers.length;
    // 隨機取一個 index
    let pick = ram(len);
    
    randomPokers.push(pokers[pick]);

    if(pick !== (len - 1)){
      pokers[pick] = pokers[len - 1]
    } 
    // pop 是 Big O(1) 比 unshift O(n) 好
    pokers.pop();

  }
  return randomPokers;
}

randomPoker(['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'], 13);

其實可以隨機抽的那兩中效率更快

function getRandomNumbers(pickNumbers=0, range = 13){
  
  let numbers = Array.from({length: range}, (_, i)=>i)
  let result = []
  
  // console.log('numbers: ', numbers)
  
  for(let i=0; i<pickNumbers; i++){
    const random = Math.floor(Math.random()*range) // 0 - 12
    result[i] = numbers[random]
    numbers[random] = numbers.pop()
  }
  
  return result
}

Last updated