سؤال

I am creating a simple math program with 6 different problem types. I want the program to randomly display one of the 6 types, but some of the problems should appear more often. I use a weighted array, but after the problem type is selected from the weighted array I am having trouble figuring out which problem type it was without using 10 or more "or" commands inside of an if statement. Here is a simplified version:

//shuffle array of 10 integers to get a random value
var rand_10 = [0,1,2,3,4,5,6,7,8,9];
fisherYates(rand_10);

//Set weightedProb
weightedProb[0] = probType[0];
weightedProb[1] = probType[0];
weightedProb[2] = probType[0];
.
.
.
weightedProb[8] = probType[0];
weightedProb[9] = probType[1];

theProblem = weightedProb[rand_10[0]];
if(rand_10[0] == 0 || rand_10[0] == 1 || rand_10[0] == 2 || rand_10[0] == 3 ||rand_10[0] == 4||rand_10[0] == 5||rand_10[0] == 6||rand_10[0] == 7||rand_10[0] == 8){
  //do something
}else if(rand_10[0] ==9){
  //do something else
}
هل كانت مفيدة؟

المحلول

Would a simple range comparison (> and <) be what you are after?

e.g.

if(rand_10[0] >= 0 && rand_10[0] <= 8){
  //do something
}else if(rand_10[0] == 9){
  //do something else
}

نصائح أخرى

You could do something like this (note indexOf isn't supported in some IE versions):

if ([0,1,2,3,4,5,6,7,8].indexOf(rand_10[0]) > -1) {
}

This is assuming the value isn't always a range and you need granular control.

why don;t you want to write so?

if(rand_10[0] >= 0 && rand_10[0] <= 8){
  //do something
}else if(rand_10[0] ==9){
  //do something else
}

arr = [ 1, 2, 3, 4, 5, 6, 7, 8]

if (rand_10[0] in arr) {
//...
}

You could also use a switch statement:

 switch(rand_10[0]) {
   case 0:
   case 1:
   case 2:
   case 3:
   case 4:
   case 5:
   case 6:
   case 7:
   case 8:
     // do something
     break;
   case 9:
     // do something
     break;
 }

Better use a function that generates weighted random index like this:

function weightedRandomIndex(weights) {
    var sum = 0, i, x, n=weights.length, rnd;
    for (i=0; i<n; i++) {
        sum += weights[i];
    }
    rnd = Math.floor(Math.random()*sum);
    for (i=0, x=0; i<n; i++) {
        x += weights[i];
        if (x > rnd) return i;
    }
}

Then you just need to specify the weights to pick your array index:

var idx = weightedRandomIndex([9,1]);  // 9 to 1 chance for index 0 over index 1
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top