sider93

Untitled

May 14th, 2016
414
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 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. public static void PrintArray(int[,] array)
  52. {
  53. int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;
  54.  
  55. for (int i = 0; i < array.GetLength(0); i++)
  56. {
  57. for (int j = 0; j < array.GetLength(1); j++)
  58. {
  59. Console.Write(array[i, j].ToString().PadLeft(n, ' '));
  60. }
  61. Console.WriteLine();
  62. }
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment