Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Everyone

I am working on a code where I need to generate 5 numbers from a given range (here between 1 to 20).

I could generate one random number as shown below and run the above code in a loop to generate 5 times, is this the right way?
Also I sometimes end up getting same numbers in the final 5 numbers.

Thanks in advance.

What I have tried:

JavaScript
<script type="text/javascript">
    $(document).ready(function () {
        $('#div').html(Math.floor(Math.random() * 6) + 1);

        var arr = [];
        for (var i = 0; i < 5; i++)
        {
            arr.push(Math.floor(Math.random() * 6) + 1)
        }
        console.log(arr);
    });
</script>
Posted
Updated 1-Dec-17 22:29pm
Comments
F-ES Sitecore 30-Nov-17 9:40am    
> is this the right way?

if you want 5 random numbers, then yes

> I sometimes end up getting same numbers in the final 5 numbers.

Why wouldn't you? It's a random number generator, not a unique random number generator and there is nothing in your code to ensure the numbers are unique. If you are only interested in unique numbers then you'll need a way of ignoring random numbers already chosen, or a way to limit the pool of possible random numbers to ensure a unique one each time. Regardless, if you google "javascript get unique random numbers" I'm sure you'll find sample code.
Kornfeld Eliyahu Peter 30-Nov-17 11:50am    
Except the [1,20] boundaries it looks good...
Review this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
Sinisa Hajnal 1-Dec-17 3:01am    
You're not generating 1-20. Other than that, code looks fine. If you need unique numbers you need an array to check for already picked numbers and need to change the loop from fixed number to while.

The following code extracts five numbers in the 1..20 range, without repetitions.
JavaScript
var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var n;
var r=[];
for (n=1; n<=5; ++n)
{
  var i = Math.floor((Math.random() * (20-n)) + 1);
  r.push(a[i]);
  a[i] = a[20-n];
}
You might try it here[^].

The algorithm is described here: Random extraction of 5 cards from a deck[^].
 
Share this answer
 
v4
Comments
Ali Al Omairi(Abu AlHassan) 6-Jun-19 4:25am    
The idea of this solution is to sortern the original array by 1 each time we pick an item, so the sample space will enshort evry time by 1 so we can add the statement a.length = 20-n; after assigning the empty slot a[i] to the last smple in the space.
The one mistake in the code abve would apeare in the statement of generating the random number becase the result would be a random number between 1 and 20 but the index of the iruginal array can be 0 to 19 so we can fix that by editing the statement to i = Math.floor(Math.rand() * (20 - n));
Try this, you can see the JS fiddle here: Edit fiddle - JSFiddle[^]

JavaScript
var arr = [];
for (var i = 0; i < 5; i++)
{
  arr.push(Math.floor(Math.random() * 20) + 1)
}

var str = "";
for (var i = 0; i < 5; i++)
{
  str += "," + arr[i];
}

var div = document.getElementById("test");
div.innerText = str;
 
Share this answer
 
Quote:
Also I sometimes end up getting same numbers in the final 5 numbers.

Random is random, it imply you can get same result more than once, just like with dices.
If you want non repeating results, it is shuffling, just like with cards, each time you draw a card, it is removed from remaining possibilities.
Shuffling - Wikipedia[^]
Fisher–Yates shuffle - Wikipedia[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900