Count By X

Create a function with two arguments that will return an array of the first n multiples of x. Assume both the given number and the number of times to count will be positive numbers greater than 0. Return the results as an array or list ( depending on language ).

Input

Our input is two numbers passed as arguments to a function.

Output

Our return value should be an array of numbers.

Explanation

This Kata contains the essentials of a function to get us started.

function countBy(x, n) {
  let z = [];
    
  return z;
}

The description of the Kata nearly gives away the answer. Since we need to do the same task a number of times we need to use a loop. In this case we’re going to use a do-while loop. A while loop checks the conditional first which gives the possibility of never running, but a do-while loop will always run once before ever checking the conditional.

function countBy(x, n) {
  let z = [];
  
  do {
    //This code runs at least once.
    z.push(x*n)
  } while ( false ) //This will breaks loop

  return z;
}

This code demonstrates the syntax we need, but it doesn’t give us our answer. Since the conditional always returns false, this loop will always run only one time. You will also notice the code in the do block is pushing a the product of x and n to the existing array. We can make this loop do what we want by changing the conditional to be true n times. We’ll need another variable that we can increment for each loop. If you do not add an incrementing variable you will end up with an infinite loop which will break things.

function countBy(x, n) {
  let z = [];
  
  let i = 1
  do {
    //This code runs at least once.
    z.push(x*n)
    i++
  } while ( i <= n ) //This is true up to and including n

  return z;
}

Now the code in the do block runs, one is added to our incrementer, then the conditional is checked. Since i goes up by one for each iteration of the loop, it will eventually end when i grows to be n+1. Now our code runs the number of times we need it to, but it’s still returning the wrong values. That’s because we never changed the x*n to include the incrementor. This is why our array is filled with the same number repeated. Here’s the final code with that gives the correct result

function countBy(x, n) {
  let z = [];
  
  let i = 1
  do {
    //This code runs at least once.
    z.push(x*i)
    i++
  } while ( i <= n ) //This is true up to and including n

  return z;
}

Simply changing the n in our original code to the incrementer, i, will gives us the output that we want.

That’s it. Good job.

Leave a Reply