lundi 20 novembre 2017

Javascript unique random number generator is not generating unique numbers

I'm trying a new random number generator that is supposed to generate numbers without duplicates, but when I try to apply it to my page it produces many duplicates. At least 60% of the time there was a dupe, one time a triplicate, and two sets of duplicates.

I'm trying the answer from Generate unique random numbers between 1 and 100 , and it seems to work as is even when I limit it to 20 numbers. Ran it 40 times with zero duplicate numbers. It's when I try to put it in my existing function that it falls apart. Any idea what I'm missing here? This is a continuation of my previous question Fill table with random images

/* The part of what each image url has in common
   ⍟ var base = 'images/Image_'
   */
var base = 'images/Image_';
var suff = '.jpg';

function randomCellBG(base) {

  // Reference the <table>
  var T = document.getElementById('mainTable');

  /* Collect all .cell into a NodeList and convert
  || it into an array
  */
  var cellArray = Array.from(T.querySelectorAll('.cell'));

  // map() the array; run a function on each loop...
  cellArray.map(function(cel, idx) {

    // Get a random number 1 - 9
    var arr = []
    while (arr.length < 5) {
      var ran = Math.ceil(Math.random() * 10)
      if (arr.indexOf(ran) > -1) continue;
      arr[arr.length] = ran;
    }

    /* Concatenate base and random number to form
    || a string of a url of an image
    ⍟ result: "images/Image_08.jpg"
    */
    var img = base + ran.toString() + suff;

    /* Assign that url as the value to the 
    || backgroundImage property of the .cell
    || in current iteration
    */
    cel.innerHTML = "<img src='" + img + "'/>";

  });

}




Aucun commentaire:

Enregistrer un commentaire