Completing a sample easy challenge from Hackerrank

Challenge:

Write a function called countUp(start) that takes a number (start) and counts upwards 10 times with all the words separated by “then”.

For example:

countUp(10);

>> 11 then 12 then 13 then 14 then 15 then 16 then 17 then 18 then 19 then 20

The Solution:

function countUp(start) {
start = start + 1;
var string = "";
process.stdout.write((start) + string);
for (var i = start+1; i < (start + 10); i++) {
string = process.stdout.write(" then " + i);
}
}

`process.stdout.write `

is equivalent to Ruby’s ‘print’ . It removes the line break.

This was a really hard coding challenge, even though it was labeled ‘Easy’.

I knew I had to print out numbers in sequence, incrementing by 1 so I decided to use a ‘for’ loop. Getting all the numbers to print out and then adding ” then ” to the end was easy. Removing the last ” then ” was hard.

I first was trying to loop adding ” then ” after the number like this:

`4 then 5 then 6 then 7 then 8 then`

But then my answer ends with the word ” then ” and that’s incorrect. So next I tried to just count up to 9 numbers and add the 10th number to the end of the string, but I kept getting an error. After much time had passed, I added ” then ” before the number so that my loop looked like this:

`then 5 then 6 then 7 then 8`

Finally, I added the ‘start’ value +1 to the beginning of the string to pass the tests.

`4 then 5 then 6 then 7 then 8`

### Like this:

Like Loading...

*Related*

I wrote it like this. Got tripped up by the STDOUT, was trying to use “puts”.

def countUp(start)

STDOUT.write((start+1..start+10).to_a.join(‘ then ‘))

end

LikeLike

Nice! I still have trouble using the STDIN and STDOUT given by Hackerrank. Great job figuring out the challenge with Ruby! Looks much simpler than JavaScript.

LikeLike