0

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))
  }
}

1
  • 1
    Create an array containing the numbers from 0 to x, select a random element of the array, then use splice to remove it. Or shuffle the array and keep using pop() Commented Jul 24, 2022 at 7:30

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.