Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Diagnostics;
  7.  
  8. namespace UlamSpiral
  9. {
  10.     class Program
  11.     {
  12.         static long[,] spiralArray = new long[10,10];
  13.         static char[] direction = new char []{ 'W', 'S', 'E', 'N' };
  14.         static long arrDimension = spiralArray.GetUpperBound(0)+1;
  15.         static long squaresToFillOnEachSide = 0;
  16.         static long colIdx = arrDimension, rowIdx = 0;
  17.         static long lastNumber = arrDimension * arrDimension;
  18.    
  19.         static void Main(string[] args)
  20.         {
  21.             Stopwatch sw = new Stopwatch();
  22.             sw.Start();
  23.             while (arrDimension > 1)
  24.             {
  25.                 squaresToFillOnEachSide = arrDimension - 1;
  26.                 for (int i = 0; i < 4; i++)
  27.                 {
  28.                     for (int j = 0; j < squaresToFillOnEachSide; j++)
  29.                     {
  30.                         if (direction[i] == 'W') { colIdx -= 1; }
  31.                         else if (direction[i] == 'S') { rowIdx += 1; }
  32.                         else if (direction[i] == 'E') { colIdx += 1; }
  33.                         else if (direction[i] == 'N') { rowIdx -= 1; }
  34.  
  35.                         spiralArray[rowIdx,colIdx]=lastNumber--;
  36.                     }
  37.  
  38.                     if (direction[i] == 'W') {colIdx -= 1; rowIdx -= 1;}
  39.                     else if (direction[i] == 'S') {rowIdx += 1; colIdx -= 1;}
  40.                     else if (direction[i] == 'E') {colIdx += 1; rowIdx += 1;}
  41.  
  42.                 }
  43.                 arrDimension -= 2;
  44.             }
  45.  
  46.             sw.Stop();
  47.             //>0 means the center box is not filled and is def on to the left
  48.             //move towars west on the same row and place the last element
  49.             if (arrDimension > 0 && lastNumber>0)
  50.             {
  51.                 spiralArray[rowIdx, colIdx-1] = lastNumber--;
  52.             }
  53.  
  54.  
  55.             for (int i = 0; i <= spiralArray.GetUpperBound(0); i++)
  56.             {
  57.                 for (int j = 0; j <= spiralArray.GetUpperBound(0); j++)
  58.                 {
  59.                     Console.Write(spiralArray[i, j] + "  ");
  60.                 }
  61.                 Console.WriteLine();
  62.             }
  63.         Console.ReadLine();
  64.         }
  65.     }
  66. }