C#, 203 202 196 193 178 bytes
n=>{var r=new int[n,n];for(int o=n-2+n%2>>1,i=r[o,o]=1,c=2,w=o,h=o,b=1-2*(i%2),j;n>i++;){r[h,w+=b]=c++;for(j=0;j<i-1;++j)r[h+=b,w]=c++;for(j=0;j<i-1;++j)r[h,w-=b]=c++;}return r;}
Saved a byte thanks to @StefanDelport.
Saved 22 bytes thanks to @FelipeNardiBatista.
This works by the following observation of how the squares are built up:
As you can see each bit is added on to the previous square. For even numbers we go right of where we were, down till were one lower than where the square was and then left to the end. Odd numbers are essentially the opposite, we go left one, up till were one above the current height and then right to the end.
Full/Formatted version:
using System;
using System.Linq;
class P
{
static void Main()
{
Func<int, int[,]> f = n =>
{
var r = new int[n, n];
for (int o = n - 2 + n % 2 >> 1, i = r[o, o] = 1, c = 2, w = o, h = o, b = 1 - 2 * (i % 2), j; n > i++;)
{
r[h, w += b] = c++;
for (j = 0; j < i - 1; ++j)
r[h += b, w] = c++;
for (j = 0; j < i - 1; ++j)
r[h, w -= b] = c++;
}
return r;
};
Console.WriteLine(String.Join("\n", f(3).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
Console.WriteLine(String.Join("\n", f(4).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
Console.WriteLine(String.Join("\n", f(5).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
Console.ReadLine();
}
}
public static class ArrayExtensions
{
public static T[][] ToJagged<T>(this T[,] value)
{
T[][] result = new T[value.GetLength(0)][];
for (int i = 0; i < value.GetLength(0); ++i)
result[i] = new T[value.GetLength(1)];
for (int i = 0; i < value.GetLength(0); ++i)
for (int j = 0; j < value.GetLength(1); ++j)
result[i][j] = value[i, j];
return result;
}
}
4Example:
4
? Or any even number. – TheLethalCoder – 2017-06-12T12:30:51.177May we output an array of arrays of ints? – TheLethalCoder – 2017-06-12T12:32:01.137
1May we assume the input is odd? – Mr. Xcoder – 2017-06-12T12:34:03.170
1Related – Emigna – 2017-06-12T12:35:58.223
Related Project Euler problem – Okx – 2017-06-12T12:36:51.387
@Okx I was inspired by that. – Julius – 2017-06-12T12:37:34.177
@TheLethalCoder I added an example for n = 4. – Julius – 2017-06-12T12:37:50.040
2Possible dupe? – Shaggy – 2017-06-12T13:10:11.340
Can the lines be outputted as an array or a sequence of cells? (asking for brainfuck) – Uriel – 2017-06-12T14:19:43.560
@Uriel No, please print the output in a grid. – Julius – 2017-06-12T18:10:20.647
1
See also http://www.perlmonks.com/?node_id=487200 with many solutions and links in replies.
– b_jonas – 2017-06-13T13:07:23.653Related: Determine the position of a non-negative number in the infinite spiral. – user202729 – 2018-03-24T04:20:36.520