0

I'm trying to create an array with random number with length of 78. I don't know how to search the entire array and check if last entry was duplicate and remove it. Someone please help.

function initAll() {
var balls = LoadInBingoBalls();
for(i=0; i < balls.length;i++)
        {
            (balls[i]);
        }
    }

function setSquare (numSquare) {
    var BingoSquare = "square" + numSquare.toString();

    document.getElementById(BingoSquare).innerHTML  = RandomNumber(MaxNo);
}

var RandomNumber = function (max) {
return Math.floor(Math.random() * max) + 1;
}

function LoadInBingoBalls(){

var first = 0;
var last = 78;
var random;

 var bag = [];

//Heres the part i get confused!
for (var i = first; i <= last; i++) {

do
         bag.push(i) = setSquare(i);

    while(bag.indexOf(i) !== -1)             
  }

 return bag;
 }
 }
zzzzBov
  • 174,988
  • 54
  • 320
  • 367

2 Answers2

2

This function will create the array and check to see if it contains the number before pushing:

working example: https://jsbin.com/cabofa/1/edit?js,console

function randNum (max) {
return Math.floor(Math.random() * max) + 1;
}

function makeArray(n) {
  var arr = [];
  while (arr.length < n) {
    var random = randNum(n);
    if (arr.indexOf(random) === -1) {
      arr.push(random);
    }
  }
  return arr;
}
omarjmh
  • 13,632
  • 6
  • 34
  • 42
0

Create an array with all the possible values:

var possibles = [];

for(i=1; i<=78; i++) {
    possibles.push(i);
}

Shuffle that array of values to be random:

function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i -= 1) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }

    return a;
}

var shuffled = shuffle(possibles);

Now pop a value from your new array to get a random element from it:

var popped = shuffled.pop();
console.log(popped);

You can call pop() as many times as you want until the array is empty, which will return undefined. For example:

for(i=0; i<shuffled.length; i++) {
    console.log(shuffled.pop());
}
Dan H
  • 3,524
  • 3
  • 35
  • 46
  • I can't see here where you have checked for duplicates... – Haroon Mehdi Apr 27 '16 at 19:30
  • No need to check for duplicates. pop() will remove the last element from the array which has already been shuffled. I have edited my answer and added a final example. Run that in a console and you will get random elements from 1 to 78 without duplicates. – Dan H Apr 27 '16 at 20:09