One warmup exercise before real HackerRank problems. Should be an easy one if you know a bit of Typescript or Javascript. I’ll do it in my way first, and check out how others did latter.
According to the description, we need to create a function which can print a string like this based on the number of the input. (0 < number ≤ 100)
#
##
###
####
If the input was 4, the function should print a right-aligned staircase composed of #
symbols with a height and width of 4.
So here is my steps:
- create an empty array
arr
storing each line of the#
we push later. - create a function who accepts the number of length and the identical charactor we want it to iterate as a string by creating an array and joinning all the charactor at the end.
- loop over the input
n
, create and push the new line composed of the prefix of blanks,#s
and the suffix of\n
intoarr
. reduce
thearr
orjoin
it if you want, and finally, print it.
Here is the code.
At first, I thought this solution was fine, but after I checked out the discussion section, I was blown away. Let’s learn some.
So here is what happened,
- We don’t actually need to create “a string” with all the
#s
inside and print them as a variable. But the testcase let me pass anyway. Array(n).fill(val, start, end)
: to create a new array with 3 parameters accepted: the value we want to fill in, the position to start, the position to end.String.repeat(n)
: to repeat a string.String.padStart
: to pad the current string with another string.
Alright, that’s all for today.