简体   繁体   中英

jQuery: how to generate 3 different random integers given limits/range?

I'm trying to generate 3 different random integers but I can't do that with jQuery, a little bit different in some ways comparing that with JS.

For example, I have 20 different questions to make in my app, but I only want to see 5 different questions, all of them random.

I look for it and I think I should use this function for that purpose:

$.randomBetween(minValue, maxValue);

but it only gives you one single number. How to get 3, between 1 and 20, being different each other?

This will give you [howMany] distinct random integers between [min] and [max]:

        var howMany = 5;
        var min = 1;
        var max = 20;
        var a = new Array();
        while (a.length < howMany) {
            var n = Math.floor(Math.random() * (max - min) + 0.5) + min;
            if (a.indexOf(n) == -1) {
                a.push(n);
            }
        }
        a.sort(function(a, b){return a-b}); // optional sorting
        console.log(a);

use one array store each random generated value in it. then check next generated value is in array or not if yes then again generate if it is not in array then store it simple

This will work:

var myArray = [];

for(var i = 0; i < 3; i++) {
    var numberIsInArray = false;
    var rand = generateRandomNumb(1, 21);
    for(var j = 0; j < myArray.length; j++){
        if(rand === myArray[j]) {
            numberIsInArray = true;
            i--;
        }
    }
    if(!numberIsInArray){
       myArray.push(rand);
    }
}

/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
function generateRandomNumb(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

You save 3 different random between 1 - 20 i myArray. Now you can do what you whant with the numbers in the array.

Try

function randomRange(from, to, leng){
    var tem, A= [], L= 0, i= 0;
    randomRangeLoop: 
    while(L< leng){
        tem= Math.floor(Math.random()*to)+from;
        i= 0;
        while(i<L){
            if(A[i++]=== tem) continue randomRangeLoop;
        }
        A[L++]= tem;
    }
    return A;
}

alert(randomRange(1, 10, 5))

The code for shuffling the array of the 20 questions is simple and I'll place it here for easy C&P

var questions = [
  'Question 1',
  'Question 2',
  'Question 3',
  'Question 4',
  'Question 5',
  'Question 6',
  'Question 7',
  'Question 8',
  'Question 9',
  'Question 10',
  'Question 11',
  'Question 12',
  'Question 13',
  'Question 14',
  'Question 15',
  'Question 16',
  'Question 17',
  'Question 18',
  'Question 19',
  'Question 20'
];

function knuthShuffle(arr){
  var idx, rand, tmp;
  // start at the end
  idx = arr.length - 1;
  while (idx) {
    /*
       Take one place after another
       reducing the number of places
       every time such that every place
       gets swapped at least once with a
       randomly chosen other place
    */
    rand = Math.floor(Math.random() * idx--);
    // swap current place with random place
    temp = arr[idx];
    arr[idx] = arr[rand];
    arr[rand] = temp;
  }
  return arr;
}
// take the first five elements of the array
var randomFiveQuestions = knuthShuffle(questions).slice(0,5);
// or take the last five ones
randomFiveQuestions = knuthShuffle(questions).slice(-5);

I use the normal implementation of the Knuth shuffle here, the first algorithm at the wiki-page.

Ah, way to late, as always ;-)

This solution demonstrates how to generate 3 random yet unique numbers. There are many ways to accomplish this. In my solution, I chose to store the collected numbers in a map. It is much more efficient to locate an element in a map O(1) than it is to determine if an element exists in a list O(n).

    var numbers = {};

    while (Object.keys(numbers).length < 3) {                // Does the numbers map contains 3 keys if not find a random unique number
        var num = Math.floor(Math.random() * 20) + 1;        // generates random number between 1 and 20 inclusive

        if (numbers[num] != "undefined") {                   // check if the number generated is already a key in the numbers map 
            numbers[num] = num;                              // add the generated number to the map
        }
    }

    console.log(Object.keys(numbers));

I finally managed to do it with your help mates, using some "if" and "for" loops when necessary. Thank you all for your answers and help. Love this page and community.

function getRandomArbitrary(min, max) {

    var limit=10;

    var values=[];

    for (var i=0; i<limit; i++) {

        var value=Math.floor(Math.random()*(max-min)+min);

        alert("Value number "+i+": "+value);

        if (i==0){
            values[i]=value;
            alert("Initial value: "+values[i]);
        }
        else{
            for (k=0;k<i;k++){
                if(value==values[k]){
                    alert("Repeated: ");
                    k=i;
                    i--;
                }
            }
            if (k==i){
                values[i]=value;
                alert("Value number "+i+" saved: "+values[i]);
            }
        }
    }

//Checking array

    for (var l=0; l<limit; l++){
        alert("Values["+l+"]: "+values[l]);
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM