0

I'm trying to generate random numbers and store the number in multi dimensional array o(need help of examples)

[ 8, 52, 9, 34, 51, 19 ] 
[ 8, 52, 9, 34, 51, 19 ]
[ 8, 52, 9, 34, 51, 19 ]
  1. What I want to achieve is to generate a sets of 6 numbers from the array and store them in numOfResults set.
  2. I want to avoid duplicate numbers generated in each the set.

Currently the code generates sets but the 3 sets are identical.

[ [ 8, 52, 9, 34, 51, 19 ], [ 8, 52, 9, 34, 51, 19 ], [ 8, 52, 9, 34, 51, 19 ] ]

My code is listed below:

    var yourNum = {
    yP : [3, 5, 8, 9, 12, 14, 17, 19, 21, 23, 26, 27, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 48, 50, 51, 52, 53, 54, 55, 57, 59],
    numOfResults: [],
    yPvalue : [],
    generateRandom: function () {
        var nRandom = Math.floor(Math.random() * (yourNum.yP.length));
        return nRandom;
    }
};

var genResults = function (num) {
    var count = num; 
    for (var i = 0; i < count; i++) {
        for (var j = 0; j < 6; j++) {
            if(yourNum.yPvalue.length < 6) {
                yourNum.yPvalue.push(yourNum.yP[yourNum.generateRandom()]);
            }
        }
        yourNum.numOfResults[i] = yourNum.yPvalue;
    }
    console.log("---------NEW---------");
    console.log(yourNum.numOfResults);
};

//var random = Math.floor(Math.random() * (yourNum.yP.length));
//var yPvalue = yourNum.yP[random];
//console.log("Your random number" + " " + random + " " + yPvalue);

genResults(3);
Vish
  • 383
  • 2
  • 8
  • 25

1 Answers1

2

You need

yourNum.yPvalue = [];

after

yourNum.numOfResults[i] = yourNum.yPvalue;

Otherwise, the multidimensional array's members will all be the same array. Hence, when your program attempts to get the next six random numbers, nothing will happen because they'd make the array longer than six elements long, something your program prevents.

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
  • Is this the only solution? Is there anything I can do without having to rewrite a call to empty the array. – Vish Nov 29 '12 at 21:09