1

I wish create a tab of number but never have the same number. Example of result wished [1,4,7,5,0,2,3,8,9,6]

I have this error :

maximum call stack size exceeded

I think it caused by recursive but I don't know what to do.

cardsAlreadyUsed = [1,4,7]

setNumCardsToUsed(cardsAlreadyUsed){
    var nbMin = 0; var nbMax = 9;
    var result = Math.floor((Math.random() * nbMax) + nbMin);
    var i = 0;

    while (i < cardsAlreadyUsed.length) {
      if (result == cardsAlreadyUsed[i]) {
        result = null;
        break;
      }
      i++;
    }
    if (result == null)
        setNumCardsToUsed(cardsAlreadyUsed);
    else
        cardsAlreadyUsed.push(result);

    return result;
};
Ben
  • 33
  • 9

2 Answers2

1

One fast way in achieving what you need is to shuffle a set of unique array.

function generateNumber() {
    var array = [0,1,2,3,4,5,6,7,8,9];
    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 makeTab() {
   var toReturn = numseries[ tabCounter ];
   tabCounter++;
   return toReturn;
}


//Counter
var tabCounter = 0;

//Generate the series of number on the pageLoad
var numseries = generateNumber();

//Call to generate new tab
var newtab = makeTab();

console.log( newtab );

So basically, on the page load, you generate the series of unique number.

If you want to generate a new tab, you can call the function makeTab();

Eddie
  • 26,593
  • 6
  • 36
  • 58
  • Sorry, I misspoke, I need to fill my tab with a new number every time I call my function, not create a full tab of random number. So with my example : I have a tab [1,8] when i call my function I want [1,8,5], if I call it a other time I want [1,8,5,2] and so on. – Ben Dec 09 '17 at 17:12
  • I updated the code. If you want to make a new tab. You can call `makeTab()` function – Eddie Dec 09 '17 at 17:14
0

You could create a range of numbers based on your min and max values, and just shuffle it.

// Create an array of integers ranging from `min` to `max` (both inclusive).
function range( min, max ){
  return Array(max - min + 1).fill().map(function(_, i){ return i + min; });
}

// Shuffle an array in place and return it.
function shuffle( a ) {
   var j, x, i;
   for (i = a.length - 1; i > 0; i--) {
      j = Math.floor(Math.random() * (i + 1));
      x = a[i];
      a[i] = a[j];
      a[j] = x;
   }
   return a;
}

// Create wanted range of integers, shuffle and return it.
function generateShuffledArray( min, max ){
   return shuffle(range(min, max));
}

console.log( generateShuffledArray(0, 9) )
pishpish
  • 2,574
  • 15
  • 22