I was watching a VueJS tutorial and was surprised at what it takes in ECMAscript to generate a random integer between 0 and 10.
Math.floor(Math.random() * 10);
In PHP it takes
mt_rand(0, 10);
In your favorite language what does it take to generate an integer between 0 and 10?
Latest comments (48)
C#
var random = new Random();var i = random.Next(0, 11);
Less elegant than some examples I'll admit
It bothers me that JS has no decent random functions and I have to reach for this bizarre mathy statement to get a random integer from a range.
Really wish we had Python's random module.
I mean, it's not hard to implement, but it's inconvenient.
The quick and dirty way in C# to get one random number is:
Keep in mind that
Random()initializes with the current timestamp so you can't use it in rapid succession and expect a random result.It's important to note what we're doing in the two functions. We're always adding a
new Random()i.eoutput.Add(new Random().Next(min, max));Why? Because we get a new timestamp when we do so.
If instead, you did something like this:
You'd end up with several repeating numbers as it's calculating off the same timestamp. This is fine for small sets of random numbers just don't go newing up
Random()for a large set.I wish JS had a more inuitive means of doing random, a built in RandInt function like Python has. Ah well.
Still beats having to make an entire object just for a random number Java.
import random
a = random.randint(0,10)
return a
Math.random() * 10 | 0;I'm a tester and I use random in my automation. In groovy, I use:
import org.apache.commons.lang.RandomStringUtils as RandomStringUtilsWebUI.setText(findTestObject('someWhereToPutNumbers'),RandomStringUtils.randomNumeric(4))
rand 0..10
Ruby
In PL/SQL:
A random number.
A random round number.
A random number between two values.
Don't trust your own computer for randomness. Better trust a webservice. ;-)