Writing Optimized Code – Part 3

Share the knowledge with others
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Hello friends, I always thought writing clean code with fewer loops is always faster than the code with lots of loops. But today I learned that it is not always true.

Let’s understand with help of an example. Consider that we need to display a below pattern as per user’s desired length (eg. 10).

*        *
 *      * 
  *    *  
   *  *   
    **    
   *  *   
  *    *  
 *      * 
*        *

In an old school method, we look to solve any pattern by taking a number of rows and number of columns. Then we look for initial spaces, stars, spaces in the middle, and stars.

The other alternative method is to look as if it is a 2D array (row, col).
0,0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9
1,0 1,1 1,2 1,3 1,4 1,5 1,6 1,7 1,8 1,9
2,0 2,1 2,2 2,3 2,4 2,5 2,6 2,7 2,8 2,9
3,0 3,1 3,2 3,3 3,4 3,5 3,6 3,7 3,8 3,9
4,0 4,1 4,2 4,3 4,4 4,5 4,6 4,7 4,8 4,9
5,0 5,1 5,2 5,3 5,4 5,5 5,6 5,7 5,8 5,9
6,0 6,1 6,2 6,3 6,4 6,5 6,6 6,7 6,8 6,9
7,0 7,1 7,2 7,3 7,4 7,5 7,6 7,7 7,8 7,9
8,0 8,1 8,2 8,3 8,4 8,5 8,6 8,7 8,8 8,9
9,0 9,1 9,2 9,3 9,4 9,5 9,6 9,7 9,8 9,9

By looking at above pattern, we can say that whereever row number is qual to column number we have * and row number + column number +1 is equals to the pattern length we have * and for the rest we have “spaces”.

Let’s look at the implementation for both the methods.

Method 1

static void DisplayPatternMethod1(int patternLength)
        {
            int leftSpacer = 0;
            int middleSpacer = patternLength - 2;
            for (int rows = 0;
                rows < patternLength/2; rows++)
            {
                for (int initialSpaces = 0; 
                    initialSpaces < leftSpacer; 
                    initialSpaces++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                for (int spaces = 0; 
                    spaces <= middleSpacer;
                    spaces++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                leftSpacer++;
                middleSpacer -= 2;
                Console.WriteLine();
            }
            //Reseting variables for bottom pattern
            if (patternLength%2==0)
            {
                leftSpacer =
                    patternLength / 2 - 1;
            }
            else
            {
                leftSpacer = 
                    patternLength / 2;
            }
            
            middleSpacer = 0;
            for (int rows = 0; 
                rows < patternLength / 2; rows++)
            {
                for (int initialSpaces = 0;
                    initialSpaces < leftSpacer;
                    initialSpaces++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                for (int spaces = 0;
                    spaces < middleSpacer; 
                    spaces++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                leftSpacer--;
                middleSpacer += 2;
                Console.WriteLine();
            }
        }

Method 2

static void DisplayPatternMethod2(int patternLength)
        {
            for (int rows = 0; 
                rows < patternLength; rows++)
            {
                for (int cols = 0; 
                    cols < patternLength; cols++)
                {
                    if (rows==cols 
                        || 
                        rows+cols+1==patternLength)
                    {
                        Console.Write("*");
                    }
                    else
                    {
                        Console.Write(" ");
                    }
                }
                Console.WriteLine();
            }
        }

Looking at the code for Method 2, it seems to be faster as it has only two loops and more clean. However, when we do actually run the Method 1 executes much faster than method 2. The below is the screenshot for pattern length 40.

Program Output
Program Output

The complete Source Code.

using System;
using System.Diagnostics;
using System.Text;

namespace WritingOptimizedCodePart3
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sbOutput = new StringBuilder();
            Console.Title = "Ankur Tech Center | Hanumantey Software Solutions";
            int patternLength = 26;
            Console.Write("Enter the " +
                "Desired Pattern Length: ");
            int.TryParse(Console.ReadLine()
                , out patternLength);
            Console.WriteLine("Displaying pattern" +
                $" using Method 1 of {patternLength}" +
                " pattern length 5 times.");
            Stopwatch sw1;
            for (int i = 0; i < 5; i++)
            {
                sw1 = new Stopwatch();
                sw1.Start();
                DisplayPatternMethod1(patternLength);
                sw1.Stop();
                sbOutput.AppendLine(
                    "Displaying pattern with " +
                "Method 1 took " +
                $"{sw1.ElapsedMilliseconds} ms.");

            }
            Console.WriteLine("Displaying pattern " +
                "using Method 2 of " +
                $"{patternLength} pattern length 5 times.");
            Stopwatch sw2;
            for (int i = 0; i < 5; i++)
            {
                sw2 = new Stopwatch();
                sw2.Start();
                DisplayPatternMethod2(patternLength);
                sw2.Stop();
                sbOutput.AppendLine(
                "Displaying pattern with" +
                " Method 2 took " +
                $"{sw2.ElapsedMilliseconds} ms.");
            }
            Console.WriteLine(sbOutput.ToString()
                );

            Console.ReadLine();
        }
        static void DisplayPatternMethod1(int patternLength)
        {
            int leftSpacer = 0;
            int middleSpacer = patternLength - 2;
            for (int rows = 0;
                rows < patternLength / 2; rows++)
            {
                for (int initialSpaces = 0;
                    initialSpaces < leftSpacer;
                    initialSpaces++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                for (int spaces = 0;
                    spaces <= middleSpacer;
                    spaces++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                leftSpacer++;
                middleSpacer -= 2;
                Console.WriteLine();
            }
            //Reseting variables for bottom pattern
            if (patternLength % 2 == 0)
            {
                leftSpacer =
                    patternLength / 2 - 1;
            }
            else
            {
                leftSpacer =
                    patternLength / 2;
            }

            middleSpacer = 0;
            for (int rows = 0;
                rows < patternLength / 2; rows++)
            {
                for (int initialSpaces = 0;
                    initialSpaces < leftSpacer;
                    initialSpaces++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                for (int spaces = 0;
                    spaces < middleSpacer;
                    spaces++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                leftSpacer--;
                middleSpacer += 2;
                Console.WriteLine();
            }
        }
        static void DisplayPatternMethod2(int patternLength)
        {
            for (int rows = 0;
                rows < patternLength; rows++)
            {
                for (int cols = 0;
                    cols < patternLength; cols++)
                {
                    if (rows != cols
                        &&
                        rows + cols + 1 != patternLength)
                    {
                        Console.Write(" ");
                    }
                    else
                    {
                        Console.Write("*");
                    }
                }
                Console.WriteLine();
            }
        }
    }
}

You can download the complete code from GitHub URL- https://github.com/ankursachdeva/WritingOptimizedCodePart3 .

Thanks for reading.


Share the knowledge with others
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply

Your email address will not be published. Required fields are marked *