Create random integers in a given range

Share this video with your friends

Social Share Links

Send Tweet

In this lesson, using TypeScript / Javascript, we learn how to solve a common problem given to new developers in interviews, generate a random number between two integers.

[00:01] Javascript math.random function provides you with a random floating point number in the range 0inclusive and 1 exclusive.

[00:09] Let's go ahead and look for a hundred times, and look at the result for math at random. You can easily scale this 0to less than 1 result to an upper limit by simple multiplication. For example, if you go ahead and multiply the result of 100, we get random values in the range 0inclusive all the way up to less than 100.

[00:40] You can limit this value to an integer if you wanted by simply using math.flow. Values in the range 0to less than 1 get chopped to 0The range 1 to less than 2 get chopped to 1, and so on till 99 to less than 100 gets chopped to 99.

[01:03] A common challenge presented to beginning developers in an interview is to go ahead and create a function that should return an integer between a given start and end value. We start off by creating a function that accepts a start value and a before value.

[01:24] We simply add start to the result that at least start is included. Next, we flow the value returned by math.random after scaling it up to the length of the start before range. As a demonstration, let's go ahead and run this function 100 times, and we can use a different start value if you wanted.