Closed ghost closed 6 years ago
I bet the author has a more efficient method than me, but I use something like this:
function randInt(fromval, toval) {
return Math.floor(fromval + myrng() * (toval - fromval));
}
randInt(3,7) -> one of 3, 4, 5, 6
function randIntIncl(fromval, toval) {
return fromval > toval ? \
Math.floor(toval + myrng() * (fromval - toval + 1)) \
: Math.floor(fromval + myrng() * (toval - fromval + 1));
}
randIntInclusive(3,7) -> one of 3, 4, 5, 6, 7
(Actually after playing around in jsperf I'm not sure there can be a faster non-native method, so...)
Thanks for the answer!
Is it possible to generate integers within a given range? Say I need numbers between 44 and 315! How can get it?