vendredi 27 octobre 2017

JavaScript - My for loop in a quote machine won't .push() a variable from another for loop into an array

I'm trying to make a weighted random number generator for a quote machine, which, if a certain item is picked, one from another set is picked without having to go in and alter all of the numbers.

Essentially, there's a main array of quotes, with numbers mixed in. These numbers correspond to lists, and they need to be more likely to be picked depending on how many items are in the list. (e.g. If 1 is picked, and corresponds to an array with ten items in it, then it should be ten times as likely to be picked as a string, because it corresponds to ten strings.)

So, I decided to convert the index from a simple unbiased random number generator into what is essentially a raffle ticket machine run by a random number generator, in which each item in the main array puts one "ticket" (or their index number for every string they have. For example, if we use the one from earlier and two other strings, it should work something like this:

input=["I am a string!",1,"Me Too!"];

output=[0,1,1,1,1,1,1,1,1,1,1,2];

A number is then randomly chosen from the output array, which then corresponds to an item in the main array. If 1 is chosen, then a string is chosen from the array 1 corresponds to.

But I plan to have a LOT of items in it. I already have upwards of forty, and plan on adding more, so I made something that makes the output array for me. The only problem is, it doesn't work right. It should output [0,1,2,3,3,3,4,6,6,6,6,7],instead it outputs [3,3,3,7,7,7,7].

//main array
var main=["one","two","three",1,"fourth",2,"fifth",3]
//array corresponding to 1
var first=["a","b","c"];
//array corresponding to 2. 2 will not be par of this array
var second=["1","2","3"];
//array corresponding to 3
var third=["red","yellow","green","blue"];
//weights
var weights=[];
//weight pusher
for (var i = 0; i < main.length; i++) {
  //weight adder
  if (!Number.isNaN(main[i])) { 
    switch (main[i]) { //If it gets to this point, main[i] should be 1, 2, or 3.
      case 1:
        //add i to the array once for every item in first (three times)
        for (var j = 0; j < first.length; j++) {
          weights.push(i)
        }
        break;
      case 2:
        //do nothing
        break;
      case 3:
        //add i to the array once for every item in third (four times)
        for (var j = 0; j < third.length; j++) {
          weights.push(i)
        }
        break;
        
    }
  }else {
    //If it's a regular string, add one i to the array.
    weights.push(i);
  };
};
console.log(weights); //Should output [0,1,2,3,3,3,4,6,6,6,6,7],instead outputs [3,3,3,7,7,7,7]



Aucun commentaire:

Enregistrer un commentaire