Advertisement
Masovski

[C# Basics][Loops-HW] 19.** Spiral Matrix

Mar 29th, 2014
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. using System;
  2.  
  3. class SpiralMatrix
  4. {
  5.     static void Main()
  6.     {
  7.         Console.Write("Enter n: ");
  8.         int n = int.Parse(Console.ReadLine());
  9.         bool inRange = n >= 1 && n <= 20;
  10.         if (inRange)
  11.         {
  12.             PrintArray(Spiral(n));
  13.         }
  14.         else
  15.         {
  16.             Console.WriteLine("Invalid input. Correct input --> 1 <= n <= 20");
  17.         }
  18.                  
  19.     }
  20.  
  21.     public static int[,] Spiral(int n)
  22.     {
  23.         int[,] result = new int[n, n];
  24.  
  25.         int pos = 1;
  26.         int count = n;
  27.         int value = -n;
  28.         int sum = -1;
  29.  
  30.         do
  31.         {
  32.             value = -1 * value / n;
  33.             for (int i = 0; i < count; i++)
  34.             {
  35.                 sum += value;
  36.                 result[sum / n, sum % n] = pos++;
  37.             }
  38.             value *= n;
  39.             count--;
  40.  
  41.             for (int i = 0; i < count; i++)
  42.             {
  43.                 sum += value;
  44.                 result[sum / n, sum % n] = pos++;
  45.             }
  46.  
  47.         } while (count > 0);
  48.  
  49.         return result;
  50.     }
  51.  
  52.  
  53.     // Method to print arrays, pads numbers so they line up in columns
  54.     public static void PrintArray(int[,] array)
  55.     {
  56.         int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;
  57.  
  58.         for (int i = 0; i < array.GetLength(0); i++)
  59.         {
  60.             for (int j = 0; j < array.GetLength(1); j++)
  61.             {
  62.                 Console.Write(array[i, j].ToString().PadLeft(n, ' '));
  63.             }
  64.             Console.WriteLine();
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement