1

I have seen this question answered here, but I have an additional question that is related.

Im trying to achieve:

the same thing, but, with the output being a selection of more than 1 number, the above works fine if you only want a single value returned.

How can I return (x) amount of outputs #7 in this case into a new var or array ...? Some guidance on best practice will also be appreciated ;)

Thanks a bunch....


Just for fun, Objective:

Create a teeny weenie web App that returns 7 variable numbers in a range [ 1 - 49 ] into an array. ` Think return a list of Lotto Numbers Create new array from selection using _underscore.js [Sample function]

**** I know this is easier, but im trying to get an understanding of using Vanilla JS to accomplish this

_.sample([1, 2, 3, 4, 5, 6], 3); => [1, 6, 2]


var getLoot = Array.from(Array(50).keys()) // Create array of 49 numbers.
console.info(getLoot);
var pick = getLoot[Math.floor(Math.random() * getLoot.length)];

pick; 

// pick returns a single which is fine if you want a single but, .. // I want something like this :

var pick = function() {
    // code that will return 7 numbers from the array into a new Array
    // will randomize every time pick is called...
}
Community
  • 1
  • 1
Hendrik
  • 137
  • 1
  • 2
  • 6

4 Answers4

2

If you want to return more than just 1 value you can store your results into a data structure like an array. Here is a solution to the problem assuming you can pass in your array of 50 numbers into the pick() funciton.:

var getRandomArbitrary = function(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

var pick = function(fiftyNumberArray, numberOfValuesWanted) {
    var randomNums = [];
    for(var i = 0; i < numberOfValuesWanted; i++) {
        randomNums.push(
            fiftyNumberArray[getRandomArbitrary(0, 50)]
        );
    }
    return randomNums;
};

var fiftyNumbers = [] // <- set your array of fifty numbers
pick(fiftyNumbers, 7);

Javascript's Math.random() will return a value in between 0 and 1 (exclusive). So to get an index scaled up to the correct value to look into your array, you would want to multiply that by the formula (max - min) + min

httpNick
  • 2,524
  • 1
  • 22
  • 34
  • It sounds like what’s wanted is a function that won’t return the same element twice. – Ry- Sep 30 '16 at 00:52
  • Oh I read `// will randomize every time pick is called...` as in, it will return a random subset of your original array, but not ensured that it is different. `pick` will always return a random set of numbers from the original 50 which I believe solves the OP's comment. – httpNick Sep 30 '16 at 00:53
  • Thanks @httpNick, that is indeed what I was looking for, and also thanks to Ryan,....it would seem that, it can also be an option ~didnt think about that. will try some permutation now ;) ....Either way thanks a lot guy's got what i was after *thumbs up* – Hendrik Sep 30 '16 at 01:00
  • 1
    @httpNick `pick` returns array where each value is `undefined`, here. Should `getRandomArbitrary` return `Math.floor(Math.random() * (max - min) + min)`? – guest271314 Sep 30 '16 at 04:12
  • 1
    you're correct, thank you @guest271314. updated my answer – httpNick Sep 30 '16 at 04:16
0

This is probably what you want.

$(function() 
{
    var lol = [1,4,5,6,7,8,9];
    function getPart(array,number)
    {
        var part = [],
            index;
        while(true)
        {
            if(part.length == number)
            {
                break;
            }
            index = $.random(0,part.length);
            part.push(lol.splice(index,1));

        }
        return part;
    }
});
$.random = function(min,max,filter)
{

    var i,
        n = Math.floor(Math.random()*(max-min+1)+min);
    if(filter != undefined && filter.constructor == Array)
    {
        for(i=filter.length-1;i>-1;i--)
        {
            if(n == filter[i])
            {
                n = Math.floor(Math.random()*(max-min+1)+min)
                i = filter.length;
            }
        }
    }
    return n;
}
Pang
  • 9,564
  • 146
  • 81
  • 122
  • That’s a lot of jQuery (?) for something that has nothing to do with jQuery and a very strange algorithm. – Ry- Sep 30 '16 at 01:19
0

You can use Array.prototype.splice(), Math.floor(), Math.random(), for loop to remove elements from input array, return an array containing pseudo randomly picked index from input array without duplicate indexes being selected.

function rand(n) {
  var res = []; var a = Array.from(Array(n).keys()); 
  for (;a.length;res.push(a.splice(Math.floor(Math.random()*a.length),1)[0]));
  return res
}

console.log(rand(50));
guest271314
  • 1
  • 15
  • 104
  • 177
  • Thanks guest271314, i still need to understand using prototypes better to be able to use it this way, but thanks will def keep it in my arsenal , – Hendrik Sep 30 '16 at 08:15
0

One good way of doing this job is shuffling the array and picking the first n values. Such as;

function shuffle(a){
  var i = a.length,
      j,
    tmp;
  while (i > 1) {
    j = Math.floor(Math.random()*i--);
    tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
  }
  return a;
};
var arr = Array(50).fill().map((_,i) => i+1); //[1,2,3...49,50]
randoms = shuffle(arr).slice(0,7)             // to get 7 random numbers from arrary arr
console.log(randoms)
Redu
  • 25,060
  • 6
  • 56
  • 76