CSharp · Console
using System;
using System.Linq;
public class Program
{
private static int[][] GetPyramidMatrix(int height)
{
// формируем рванный двумерный массив
// последовательно увеличиваем размер строк на 2
// на верхнем ярусе 1 элемент, дальше 3, потом 5 и т.д.
int size = -1;
int[][] arr = new int[height][];
for (int i = 0; i < height; i++)
{
size += 2;
arr[i] = new int[size];
for (int k = 0; k < size; k++)
{
arr[i][k] = 0;
}
}
return arr;
}
private static int CountOfDigits(int number)
{
return (int)Math.Floor(Math.Log10(number) + 1);
}
private static void DisplayPyramid(int[][] arr)
{
int height = arr.Length;
int width = arr[height - 1].Length;
int indent = width / 2;
int maxValue = arr.SelectMany(x => x).Max();
int maxCountOfDigit = CountOfDigits(maxValue);
string spaceFormat = new string(' ', maxCountOfDigit + 1);
for (int i = 0; i < height; i++)
{
for (int j = 0; j < indent; j++)
{
Console.Write(spaceFormat);
}
for (int k = 0; k < arr[i].Length; k++)
{
int curCountOfDigit = CountOfDigits(arr[i][k]);
string curSpaceFormat = new string(' ', maxCountOfDigit - curCountOfDigit);
Console.Write(string.Format("{0} " + curSpaceFormat, arr[i][k]));
}
Console.WriteLine();
indent -= 1;
}
}
public static void BuildPyramid(int height)
{
// частный случай
if (height == 1)
{
Console.Write("1");
return;
}
int[][] arr = GetPyramidMatrix(height);
int pyramidWidth = arr[height - 1].Length;
// переменные направления
int bottom = height - 1;
int top = 0, left = 0;
int right = pyramidWidth;
// идем по строкам сверху и снизу
int block = 0;
while (top < bottom)
{
// идем слева направо
for (int i = left; i < right; ++i)
{
block += 1;
arr[bottom][i] = block;
}
// дальше идем наверх по правой стороне пирамиды
for (int i = bottom - 1, side = right - 1; i >= top; --i)
{
side -= 2;
block += 1;
arr[i][side] = block;
}
// спускаемся вниз по левой стороне пирамиды
for (int i = top + 1; i < bottom; ++i)
{
block += 1;
arr[i][left] = block;
}
// двигаемся дальше
++top;
++left;
--bottom;
// уменьшаем на -1, и также вычитаем -2
// т.к. каждый верхний ярус пирамиды меньше нижнего на 2 блока
right -= 3;
}
// частный случай: для пирамиды с нечетной высотой
// остается сердцевина из 1го блока
if (height % 2 != 0)
{
int row = height / 2;
int col = arr[row].Length / 2;
arr[row][col] = ++block;
}
// визуализируем пирамиду
DisplayPyramid(arr);
}
public static void Main()
{
Console.WriteLine("UniLecs");
BuildPyramid(2);
Console.WriteLine();
BuildPyramid(3);
Console.WriteLine();
BuildPyramid(4);
Console.WriteLine();
BuildPyramid(15);
Console.WriteLine();
}
}