How to Randomly Choose an Element from an Array that Wasn't Chosen before in JavaScript?

前端 未结 4 1015
遥遥无期
遥遥无期 2020-12-22 05:25

I want to run a function that each time randomly chooses an element from an array that wasn\'t chosen before. And if all elements were chosen, I want to reset the used eleme

4条回答
  •  独厮守ぢ
    2020-12-22 05:52

    The easiest way to handle this is:

    • Shuffle the array (also link here). I've taken the implementation directly from this answer and removed the comments for brevity.
    • Maintain an index for the current item.
    • When getting the next item, fetch the index and increment to the next one.
    • Once you finish with the array, return the index to the start and re-shuffle the array.

    function shuffle(array) {
      var currentIndex = array.length, temporaryValue, randomIndex;
    
      while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
    
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
      }
    
      return array;
    }
    
    
    var items = ["alpha", "beta", "gamma", "delta", "epsilon"];
    var index = Infinity;
    
    function start() {
      console.log("----- shuffling -----")
      shuffle(items);
      index = 0;
    }
    
    function nextItem() {
      if (index >= items.length) {
        //re-start
        start()
      }
      
      //return current index and increment
      return items[index++];
    }
    
    document.getElementById("click_me")
      .addEventListener("click", function() {
        console.log(nextItem())
      })

    This can also be converted to a generator function

    function shuffle(array) {
      var currentIndex = array.length, temporaryValue, randomIndex;
    
      while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
    
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
      }
    
      return array;
    }
    
    function* random(array) {
      let index = Infinity;
      const items = array.slice(); //take a copy of the array;
      
      while(true) {
        if (index >= array.length) {
          console.log("----- shuffling -----")
          shuffle(items);
          index = 0;
        }
        
        yield items[index++];
      }
    }
    
    
    var items = ["alpha", "beta", "gamma", "delta", "epsilon"];
    
    //start the generator
    const generateRandom = random(items);
    
    document.getElementById("click_me")
      .addEventListener("click", function() {
        console.log(generateRandom.next().value)
      })

提交回复
热议问题