1

I would like to know how to exclude a number from being chosen randomly from an array. The number has to be previously selected from a listing in html format such as the one shown below. If, for example I choose the number "05" I would like it to be excluded from the random selection process. I've also attached the js code of the random pick. Thanks.

           <SELECT ID="elegirNombre" NAME="elección">
                   <OPTION ID="01" VALUE="01">01</OPTION>
                   <OPTION ID="02" VALUE="02">02</OPTION>
                   <OPTION ID="03" VALUE="03">03</OPTION>
                   <OPTION ID="04" VALUE="04">04</OPTION>
                   <OPTION ID="05" VALUE="05">05</OPTION>
                   <OPTION ID="06" VALUE="06">06</OPTION>
                   <OPTION ID="07" VALUE="07">07</OPTION>
                   <OPTION ID="08" VALUE="08">08</OPTION>
                   <OPTION ID="09" VALUE="09">09</OPTION>
                 </SELECT><BR /><BR />
var bunchofnumbers = ['01', 'C02', '03', '04', '05', '06', '07', '08', '09'];
var rand = bunchofnumbers[Math.floor(Math.random() * bunchofnumbers.length)];
alert("Your number is: " + rand) ;       




Jake Worth
  • 5,490
  • 1
  • 25
  • 35

3 Answers3

2

you can write an exclude function like:

function randomExcludedNumber(numLength, excludeNumber) {
    var randNumber = excludeNumber;
    While(randNumber == excludeNumber)
    {
       randNumber = Math.floor(Math.random() * numLength)
    }
    return randNumber ;
  }

Then you can use it like:

 var bunchofnumbers = ['01', 'C02', '03', '04', '05', '06', '07', '08', '09']
 var selectedIndex = bunchofnumbers.indexOf("04"); //get selected value index
 var randomNum = randomExcludedNumber(bunchofnumbers.length, selectedIndex );
 var rand = bunchofnumbers[randomNum];
 alert("Your number is: " + rand) ;  

Here is a working Demo: Fiddle

Luthando Ntsekwa
  • 4,192
  • 6
  • 23
  • 52
0

You can remove the element you dont want to be chosen from the array with this code

var index = bunchofnumbers.indexOf('element you dont want');
if (index > -1) {
  bunchofnumbers.splice(index, 1);
}

bunchofnumbers then wont have that element, and therefore wont be chosen. you can always make a copy of the original array if you want.

0

SOLUTION:

The following code chooses random element and removes the chosen element.

let bunchofnumbers = ['01', '02', '03', '04', '05', '06', '07', '08', '09'];
let randIndex = Math.floor(Math.random() * bunchofnumbers.length);
let valueChosen = bunchofnumbers[randIndex];
bunchofnumbers.splice(randIndex, 1); // removes chosen value from array
alert("Chosen/removed element is: " + valueChosen + " (bunchofnumbers: " + bunchofnumbers + ")");
Naveen Kumar V
  • 2,559
  • 2
  • 29
  • 43