Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Create random integers in a given range

    Basarat Ali SyedBasarat Ali Syed

    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.

    typescriptTypeScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss