Forum Discussion
4 Replies
Sort By
- karkadilValued ContributorThis JScript function will generate a random integer within a given interval
function randInt(min, max)
{
return Math.round(Math.random()*(max-min)+min)
}
method Math.random() returns a random number between 0 and 1 - OfervSuper ContributorHi,
is there a way to generate random number from a range of numbers but do it twice and make sure the first number won't be selected twice?
for example:
if i have the numbers:1,2,3,4,5,6,7,8,9 and the random function select the number 4,i want to run this function again and make sure that the number 4 won't be selected again
Thanks - karkadilValued ContributorHere is an example of such code using the randInt() function I provided earlier.
function generateTwoNumbers()
{
var n1, n2;
n1 = n2 = randInt(1, 9);
while(n2 == n1)
{
n2 = randInt(1, 9);
}
}
Hi,
I agree with Gennadiy - his solution is simple and clear. Also, if the number of elements to select is high, you may use a different approach:
Use an array of N possible values (may be generated programmatically), pick an index randomly in the [0..N-1] range, use the value having that index, then delete the value from the array, and pick another random index in the [0..N-2] range. This can be done in a loop to generate lengthy values with different digits.
Related Content
Recent Discussions
- 14 hours agoAivanitskiy
- 17 hours agonastester