Algorithms and Data Structures – Steps

--- Directions
Write a function that accepts a positive number N.
The function should console log a step shape
with N levels using the # character. Make sure the
step has spaces on the right hand side!
--- Examples
steps(2)
'# '
'##'
steps(3)
'# '
'## '
'###'
steps(4)
'# '
'## '
'### '
'####'
Solution 1. Make a Matrix
  1. From 0 to n (iterate through row)
    1.1 Create an empty string 'stair'
    1.2 From 0 to n (iterate through column)
    IF the current column is equal to or less than the current row
    add a "#" to 'stair'
    Else
    add a space to 'stair'
  2. consol log 'stair'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function steps(n) {
  for (let row = 0; row < n; row++) {
    let stair = '';
    for (let column = 0; column < n; column++) {
      if (column <= row) {
        stair += '#';
      } else {
        stair += ' ';
      }
    }
    console.log(stair);
  }
}
cs

 

Solution 2. Recursion

recursion tip!

  • Figure out the bare minimum pieces of information to represent your problem
  • Give reasonable defaults to the bare minimum pieces of info
  • Check the base case. is there any work left to do? if not, return
  • Do some work, Call your function again, make sure the arguments have changed in some fashion

 

  1. if (row ===n) then we hit the end of our problem
  2. if the 'stair' has a length === n then we are at the end of row
  3. if the length of the stair string is less than or equal to the row number we're working on, we add a '#', otherwise add aspace
1
2
3
4
5
6
7
8
9
10
11
12
13
function steps(n, row = 0, stair = '') {
  if (n === row) {
    return;
  }
  if (n === stair.length) {
    console.log(stair);
    return steps(n, row + 1);
  }
  const add = stair.length <= row ? '#' : ' ';
  steps(n, row, stair + add);
}
cs

Leave a Comment

en_USEnglish