Monday, April 4, 2016

C# console app to print numbers in counter clockwise - spiral modle

Hi Guys,

I have created a sample code to print given number (n) with 2 into n. (Ex enter 4, it print 2 into 4 -1 in spiral model). Give a try!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyTry
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter integer: ");
            int n = int.Parse(Console.ReadLine());
            int[,] matrix = new int[n, n];
            int row = n - 1;
            int col = 0;
            string direction = "right";
            int maxRotations = n * n;

            for (int i = 1; i <= maxRotations; i++)
            {
                if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))
                {                
                    direction = "up";
                    col--;
                    row--;
                }
                if (direction == "down" && (row > n - 1 || matrix[row, col] != 0))
                {
                    direction = "right";
                    row--;
                    col++;
                }
                if (direction == "left" && (col < 0 || matrix[row, col] != 0))
                {
                    direction = "down";
                    col++;
                    row++;
                }

                if (direction == "up" && (row < 0 || matrix[row, col] != 0))
                {
                    direction = "left";
                    row++;
                    col--;                  
                }

                matrix[row, col] = i;
             
                if (direction == "right")
                {
                    col++;
                }
                if (direction == "down")
                {
                    row++;
                }
                if (direction == "left")
                {
                    col--;
                }
                if (direction == "up")
                {
                    row--;
                }
            }

            // Display Matrix

            for (int r = 0; r < n ; r++)
            {
                for (int c = 0; c < n; c++)
                {
                    Console.Write("{0,4}", matrix[r, c] - 1);
                }
                Console.WriteLine();
            }

         
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment