Monday, July 22, 2013

Novel Approach to Nested Loops

Yesterday my Udacity.com Introduction to Programming course introduced the following nested loop problem:

Write a nested-loop that creates a triangle pattern based on the number of rows input by the user such that the nth row has n ASCII-art boxes.
Examples: 
 if n = 1
[]
if n = 3
[]
[][]
[][][]
if n = 8
[]
[][]
[][][]
[][][][]
[][][][][]
[][][][][][]
[][][][][][][]
[][][][][][][][]

My initial approach to this problem was that it would be fairly easy to keep track of each row, however the number of "[]" would be less simple to track due to their inflating nature by row.  Since the number of "[]" per row would be dependent upon row number, I chose to implement a while loop that compared some integer i counting up from 0 until it reached the given row as dictated by a for loop, seen below:

for (int row = 1; row <= userInput; row++)
{
    int i = 1;
    while (i <= row)
    {
        System.out.print("[]");
    }
    System.out.println();
}

While the above code works, the solution provided by the professor took me as more elegant, and the approach the professor used was far more intuitive as well.  The summary of the approach is as follows:


  1. Determine the for loop solution to writing the first row of "[]"
  2. Determine the for loop solution to writing the second row of "[]"
  3. Intuit from the similarity/dissimilarity of the for loops from 1 & 2 the nested for loop solution
  4. Write the code necessary for the final solution
The above approach applies to the stated triangle pattern problem as follows:


  1. for (int i = 1; i <= 1; i++) { System.out.print("[]") } //code necessary to print row 1
  2. for (int i = 1; i <= 2; i++) { System.out.print("[]") } //code necessary to print row 2
  3. The only difference between 1 & 2 is the comparison expression of the for loop.  The intuition is that the non-i value of the comparison expression can be replaced by the row value.  Therefore the solution involves replacing the comparison terminating value with row and nesting the above loop in another for loop that steps through all of the possible values of row.
  4.  
for (int row = 1; row <= userInput; row++)

{
    for (int i=1; i <= row; i++)
    {
        System.out.print("[]");
    }
    System.out.println();
}


I am certain this approach will provide a more cohesive and logical approach to determining correct and efficient nested for loop solutions in the future.

No comments:

Post a Comment