Home > Mobile >  How to prevent repeating random numbers in Vue 3 and JavaScript
How to prevent repeating random numbers in Vue 3 and JavaScript

Time:07-25

I am attempting to build a function that loops through a series of array objects containing names and ids after the array objects have been randomized, then returns a single filtered item to slots.value. So far, my spin function works in terms of looping through the randomized objects. However, the line const index = Math.floor(Math.random() * list.length) occasionally returns the same index number twice in a row. I wish to prevent the random index function from returning the same index number twice in a row. How can I do this?

const slots = ref([])

const names = ref([
  { name: 'Leslie', id: 1 },
  { name: `Ron`, id: 2 },
  { name: 'April', id: 3 },
  { name: 'Andy', id: 4 },
  { name: 'Tom', id: 5 },
  { name: 'Jerry', id: 6 },
])

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

const spin = async () => {
  const list = names.value.sort(() => Math.random() - 0.5)
  const newArray = []

  for (let i = 0; i < list.length; i  ) {
    const index = Math.floor(Math.random() * list.length)
    await sleep(100)
    slots.value = list.filter(r => r.id === (index   1))
  }
}

CodePudding user response:

One solution is to re-generate the index if the new value matches the previous one:

let prevIndex = null
const generateRandIndex = max => {
  let index
  do {
    index = Math.floor(Math.random() * max)
  } while (index === prevIndex)
  prevIndex = index
  return index
}

const spin = async () => {
  ⋮
  for (let i = 0; i < list.length; i  ) {
    const index = generateRandIndex(list.length)
    ⋮
  }
}

demo

  • Related