tags:

views:

49

answers:

3

I have 100 values in an array but I need to select 5 value randomly on every click one button and I have one value e.g a=10 this a value shouldn't come in the 5 selected value.

I tried in different way but I am not able to do it in jquery. please any help me.

+2  A: 

Dunno, if it strictly needs to be jQuery, but here is a pure JS solution. "input" is the array holding the 100 values.

var output = [];

for (var i = 0, len = input.length; i < 5; ++i) {
 var randomIndex = Math.floor(Math.random() * input.length);

 if (input[randomIndex] != 10) {
  output.push(input[randomIndex);
 }
}
softcr
its jquery scripting?
Elankeeran
A: 

You can also resort randomly the original array

function reorder(src) {
    return src.sort(function (a, b) { return 1 - (Math.random() * 2); });
}

and you can get the top 5 like this:

yourArray = reorder(yourArray).slice(0, 5);
Jhonny D. Cano -Leftware-
+1  A: 

The following code may help. The calculateRandoms function calculates 5 different random numbers from the numbers array each time. The random number cannot be value of excludedNumber. You can change randomCount variable to modify the number of random numbers that calculateRandoms will generate.

  var excludedNumber = 10;
  var randomCount = 5;
  var numbers = [];
  var randoms = [];
  // initialize array, fill it from 0 to 99
  for (var i = 0; i < 100; i++) numbers.push(i + 1);
  $(document).ready(function() {
      var btn = $("#mybutton");
      btn.click(function() { calculateRandoms(randomCount); })
  });
  function calculateRandoms(c) {
      randoms = [];
      for (var i = 0; i < c; i++) {
          var rnd = excludedNumber;
          while (rnd == excludedNumber && $.inArray(rnd, numbers)) rnd = numbers[Math.floor(Math.random() * numbers.length)];
          randoms.push(rnd);
      }
  }
Zafer
By the way, calculateRandoms uses the method, jquery.inArray to look up for a value in the array.
Zafer