using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace UlamSpiral { class Program { static long[,] spiralArray = new long[10,10]; static char[] direction = new char []{ 'W', 'S', 'E', 'N' }; static long arrDimension = spiralArray.GetUpperBound(0)+1; static long squaresToFillOnEachSide = 0; static long colIdx = arrDimension, rowIdx = 0; static long lastNumber = arrDimension * arrDimension; static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); while (arrDimension > 1) { squaresToFillOnEachSide = arrDimension - 1; for (int i = 0; i < 4; i++) { for (int j = 0; j < squaresToFillOnEachSide; j++) { if (direction[i] == 'W') { colIdx -= 1; } else if (direction[i] == 'S') { rowIdx += 1; } else if (direction[i] == 'E') { colIdx += 1; } else if (direction[i] == 'N') { rowIdx -= 1; } spiralArray[rowIdx,colIdx]=lastNumber--; } if (direction[i] == 'W') {colIdx -= 1; rowIdx -= 1;} else if (direction[i] == 'S') {rowIdx += 1; colIdx -= 1;} else if (direction[i] == 'E') {colIdx += 1; rowIdx += 1;} } arrDimension -= 2; } sw.Stop(); //>0 means the center box is not filled and is def on to the left //move towars west on the same row and place the last element if (arrDimension > 0 && lastNumber>0) { spiralArray[rowIdx, colIdx-1] = lastNumber--; } for (int i = 0; i <= spiralArray.GetUpperBound(0); i++) { for (int j = 0; j <= spiralArray.GetUpperBound(0); j++) { Console.Write(spiralArray[i, j] + " "); } Console.WriteLine(); } Console.ReadLine(); } } }