JavaScript Algorithm: Generate Range of Integers

Erica N
Erica N
Mar 17, 2020 · 2 min read
Image for post
Image for post

For today’s algorithm, we are going to write a function called generateRange that will take three integers, min, max, and step as input.

Using those three integer inputs, generate a range of integers from min to max but after each certain number of steps. The function will output these numbers in an array. The range output, depending on the step count, does not have to include the max. Let’s look at an example:

let min = 2;
let max = 12;
let step = 3;

For our example above we count from 2 to 12 but if we count every third number after 2, we get the following numbers:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
// [2, 5, 8, 11]

The function will output: [2, 5, 8, 11].

Now, we move on to solving this algorithm with code.

We are going to create an empty array and assign it to the variable, arr.

let arr = [];

Then we will use the for-loop. With our initial number being min, we keep looping until we reach our max, only outputting numbers every step times.

for(let i = min; i <= max; i += step){
arr.push(i);
}

We push all of those numbers into our arr array. After the loop is done, we return our array.

return arr;

In this function, we learned how to create an array and fill it with numbers based on our for-loop. With our for-loop, our initial value doesn’t always have to be 0. The same with our increment. Instead of using i++ , if you wanted to increment by a number higher than 1, you’ll use the addition assignment operator, +=. Writing i += 2 is the same as writing i = i + 2.

And that concludes our function. Here is the rest of the code:

function generateRange(min, max, step){
let arr = [];
for(let i = min; i <= max; i += step){
arr.push(i);
}

return arr;
}

If you found this algorithm helpful, check out my other recent JavaScript algorithm solutions:

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store