The Staircase Problem

So, the journey continues. This problem is a bit of a doozy, because it is something that requires deeper thought on the functionality of the script that you write (or function, whichever you choose to call it). This solution will be coded in JavaScript.

Problem Statement:

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 that the step has spaces on the right-hand side.

Examples:

steps(2)

 '# '

 '##'


steps(3)

'#  '

'## '

'###'


steps(4)

'#   '
'##  '
'### '
'####'

So, we are tasked with building an algorithm that follows this pattern.

Step 1:

Note: The indices for the columns and rows will start at position 0, not 1.

The first thing that we must do is break the problem into two parts, namely the columns and rows that will build our staircase. In the second example, when n = 3, the first step of the staircase receives a '#' in the first square, and a space in the second. Another way of saying this is that, at Row[0], we see a '#', and at Col[0], we see a '#.' However, on the next step, we see the beginning of a pattern.

On the second step, we see a space. This means that, at position Row[0], Col[1], we see a space. Now, this is not enough to see a pattern, so let's continue.

On the third step, we see '#' in each row and each column.

  1. Row[0], Col[0]
  2. Row[1], Col[1]
  3. Row[2], Col[2]

Here, we can draw two conclusions.

  1. When the Column index is less than or equal to the Row index, we put a '#.'
  2. However, when the Row index is higher than the Col index, we want to console.log a space. For example, at Row[0], Col[1], we have a space. This is the same at position Row[0], Col[2], and so forth.

Step 2:

Now, we must create a function that recognizes this pattern, and outputs the logs to create this staircase of '#.' Yes, this will require iteration.

First, we are going to iterate over the Rows in our matrix. So, the setup will look like this:

function staircase(n) {

  for(let row = 0; row < n; row++){

    //our code here
    
  }
        
}

So, first, a few notes. We are setting Row equal to 0, because, as mentioned above, this will represent the first index for our Row. Next, as with many iterations, our Row index value will be less than the given number, 'n.' This is due to the fact that the given number, 'n', does not take into account that our index is starting at 0. Therefore, we are essentially creating the statement that this iteration will run until it is 1 less than n. This makes sense, because, in the example where 'n' is set equal to 3, we iterate three times starting from 0. If we iterated n number of times starting from 1, we would only complete 2 iterations before the conditional stops the loop, because Row cannot be equal to 'n.' That might've been a bit wordy, but the logic here is valid.

Now, we must set up what we want to log out.

Step 3:

The end goal of this function is to console.log the staircase using the '#' symbol. This means that we do NOT want to return a string of '#' characters, but we CAN console.log a string that represents the staircase. So, the next step is to create this variable of an empty string, which we will call 'stair.'

function staircase(n) {

  for(let row = 0; row < n; row++){

    let stair = '';
    
  }
        
}

This stair string is what we will console.log at each iteration.

Step 4:

Now, we have laid the groundwork for sifting through the Rows, but we must not forget about the Columns. So, we will create a nested for loop that will consider BOTH the Row and the Column at each index until the condition is met. We will use the logic above to create this second loop.

function staircase(n) {

  for(let row = 0; row < n; row++){

    let stair = '';

    for(let col = 0; col < n; col++){

      //our code here
      
    }
                  
  }
                      
}

This second loop will run until Column is one less than 'n,' and starts with index 0.

Step 5:

Now, we put into practice our logic from above, which yields us a two-part conditional.

  1. If Col index is less than OR equal to Row index, than we put a '#'.
  2. If this condition is not met, then we place a space (' ').
function staircase(n) {

  for(let row = 0; row < n; row++){

    let stair = '';

    for(let col = 0; col < n; col++){

      if(col <= row){

       stair += '#';
                                        
      } else {

        stair += ' ';

      }
                                                  
    }
  }
}

Step 6:

Now, for the final act. Our nested for loops will build our staircase using the string stair, and all that we need to do is console.log the resulting string at each iteration.

function staircase(n) {

  for(let row = 0; row < n; row++){

    let stair = '';

    for(let col = 0; col < n; col++){

      if(col <= row){

       stair += '#';
                                        
      } else {

        stair += ' ';

      }
                                                  
    }

    console.log(stair);

  }
}

Now, there is also a recursive solution to this problem, in which the function calls itself. I want to get a better handle on that before I try to explain it, so I will keep you posted.

要查看或添加评论,请登录

Michael John Schiuma的更多文章

  • Job/Soul Searching

    Job/Soul Searching

    If you're like me, you don't particularly enjoy the process of searching for jobs. The rejections begin to pile up, and…

    2 条评论
  • Chunked Solution #1 - Arrays and SubArrays

    Chunked Solution #1 - Arrays and SubArrays

    Continuing in the quest to pass a technical interview, here is another sample problem. Today, we are going to take on a…

  • Big-0 and Technical Interviews

    Big-0 and Technical Interviews

    Well, I recently had my first practice technical interview. To say that it was difficult is a gross understatement.

    5 条评论
  • The "MaxChars" Problem

    The "MaxChars" Problem

    The interview preparation continues. Today, I am going to go through a short example of a common problem that is used…

  • Palindromes

    Palindromes

    I think that I will create a small series of posts in which I tackle and explain how to solve common coding questions…

  • Reverse String Coding Challenge

    Reverse String Coding Challenge

    I don't know about you, but the idea of going through software-engineering interviews is daunting and nerve-wracking…

    4 条评论
  • Promises...and Why We Need to Resolve Them

    Promises...and Why We Need to Resolve Them

    Today, we embark on the journey of figuring out promises, and I promise to resolve it (pun indubitably intended)…

  • Рафаэла

    Рафаэла

    Как важна бабушка своим внучатам. Единственный способ измерить – посчитать мгновения, звонки на дни рождения…

  • Understanding Redux Data Flow

    Understanding Redux Data Flow

    Redux can often seem complicated for one simple reason - there is a lot going on behind the scenes that may not always…

  • The Resource Curse: How Russia's Greatest Blessing Became Its Biggest Curse

    The Resource Curse: How Russia's Greatest Blessing Became Its Biggest Curse

    Click here.

社区洞察

其他会员也浏览了