Lottery ticket picker (v2)

Revision 2 of this benchmark created on


Setup

const randomBall = () => Math.floor(Math.random() * 59) + 1

function generateRandomNumbers(count, max) {
    let arr = Array.from({length: max}, (_, i) => i + 1);
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]]; // Swap
    }
    return arr.slice(0, count);
}

Test runner

Ready to run.

Testing in
TestOps/sec
Sort and Slice
  let numbers = Array.from({ length: 59 }, (_, i) => i + 1)
  // shuffle the array
  numbers = numbers.sort(() => Math.random() - 0.5)
  // take the first 6 numbers
  const ticket = numbers.slice(0, 6)
  const bonus = ticket.pop()
  return {ticket, bonus}
ready
While checking
  const ticket = []
  // numbers must be unique
  for (let i = 0; i < 6; i++) {
    let ball = randomBall()
    while (ticket.includes(ball)) {
      ball = randomBall()
    }
    ticket.push(ball)
  }
  let bonus = randomBall()
      while (ticket.includes(bonus)) {
      bonus = randomBall()
    }
    return {ticket, bonus}
ready
Pick unique random
  let numbers = Array.from({ length: 59 }, (_, i) => i + 1)
  let ticket = []
  // pick out unique numbers
  for (let i = 0; i < 6; i++) {
    const index = Math.floor(Math.random() * numbers.length)
    ticket.push(numbers[index])
    numbers.splice(index, 1)
  }
  let bonus = numbers[Math.floor(Math.random() * numbers.length)]
  return {ticket, bonus}
ready
While with obj
  let ticket = {}
  // numbers must be unique
  for (let i = 0; i < 6; i++) {
    let ball = randomBall()
    while (ticket[ball]) {
      ball = randomBall()
    }
    ticket[ball] = true
  }
  let bonus = randomBall()
    while (ticket[bonus]) {
      bonus = randomBall()
    }
    return {ticket, bonus}
ready
Sets
let uniqueNumbers = new Set();
while(uniqueNumbers.size < 6) {
    uniqueNumbers.add(Math.floor(Math.random() * 59) + 1);
}
let result = Array.from(uniqueNumbers);
ready
Fisher-Yates slice
const randomNumbers = generateRandomNumbers(6, 59);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.