-1

My table generates 7 random boxes in blue, and 5 other random boxes in yellow, but my problem is that sometimes a boxd "Id" can have 2 or 3 times the same random value, and we see only 5 blue boxes, not 7 as expected. How can I fix it? If the boxe is blue, it can not be a second time, if it is blue, it can not be yellow, etc.

function bluecolor() {
  $(".boutton2").click(function() {
      for (i = 0; i < 7; i++) {
        var rn = Math.floor(Math.random() * 28) + 1;

        $("#" + rn).addClass("blue");
      }
      for (a = 0; a < 5; a++) {
        var randome = Math.floor(Math.random() * 28) + 1;
        $("#" + randome).addClass("yellow");
      }
    }
  }
Pedram
  • 15,766
  • 10
  • 44
  • 73
Aria
  • 33
  • 4

3 Answers3

2

I see in your code that seems you have 29 boxes, not 12, numbered from 1 to 29. I understant that you want 7 of them in blue and 5 in yellow. Right?

You could make an array with the 28 ids (numbers 1 to 29), them "shuffle" it, and asign class blue to the first 7, yellow to the next 5... (and remove the classes for the others if needed).

(take a look to How can I shuffle an array?)

miguel-svq
  • 2,136
  • 9
  • 11
0

You can use $("#" + randome).length > 0 to verify if the id is already added or $(".myClass").length > 0 if you want use a class for this.

You can also use a array and verify the numbers and just pick different numbers.

var numbers = [];

while(numbers.length < 5){
   var number = Math.floor(Math.random() * 28) + 1;
   if(numbers.indexOf(number) == -1){
      numbers.push(number);
   }
}
console.log(numbers);

You can make a function and use multiple times:

function getRandomNotEqualNumbers(quantity, max, min){
  var numbers = [];

  while(numbers.length < quantity){
     var number = Math.floor(Math.random() * max) + min;
    if(numbers.indexOf(number) == -1){
       numbers.push(number);
    }
  }
  return numbers;
}

var blues = getRandomNotEqualNumbers(7, 28, 1);
var yellows = getRandomNotEqualNumbers(5, 28, 1);

console.log(blues);
console.log(yellows);

//if you want unique between colors
var myNumbers = getRandomNotEqualNumbers(12, 28, 1);
blues = [];
yellows = [];
for(var i = 0; i < myNumbers.length; i++){
  if(i < 7)
    blues[i] = myNumbers[i];
  else
    yellows[i-7] = myNumbers[i];
}

console.log(blues);
console.log(yellows);
Ciro Spaciari
  • 630
  • 5
  • 10
  • It works for only one color, how can I make it for 2 colors ?.. Blue and Yellow – Aria Dec 17 '17 at 13:34
  • run this twice? i will create a function to make more clear – Ciro Spaciari Dec 17 '17 at 13:37
  • No I mean, I have 7 blue and 5 yellow that's ok, but some times I have 5 blue and 5 yellow, should I create a big "while" chich containes the two colors ? – Aria Dec 17 '17 at 13:40
0

To avoid repeating numbers make an arraylist with every number you generate.