Skip to content

Instantly share code, notes, and snippets.

@ff8c00
Created June 22, 2017 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ff8c00/9352e63822c0148ea9bbd79fdf52d0fe to your computer and use it in GitHub Desktop.
Save ff8c00/9352e63822c0148ea9bbd79fdf52d0fe to your computer and use it in GitHub Desktop.
Reddit Daily Programmer 320 Easy
using System;
using System.Linq;
namespace Reddit
{
internal static class Easy
{
internal static void Run(int input)
{
Run(input, true);
}
internal static void Run(int input, bool clockwise)
{
int[][] spiral = Build(input);
if (!clockwise)
{
int[][] opposite = new int[input][];
for (int i = 0; i < input; i++)
{
opposite[i] = new int[input];
for (int j = 0; j < input; j++)
{
opposite[i][j] = spiral[j][i];
}
}
spiral = opposite;
}
var items = spiral
.Select(r => r
.Select(c => c.ToString())
.ToList())
.ToList();
int width = items.SelectMany(e => e).Max(e => e.Length);
foreach (var item in items)
{
Console.WriteLine(string.Join(" ",
item.Select(e => e.PadLeft(width))));
}
}
internal static int[][] Build(int input)
{
const int east = 0, south = 1, west = 2, north = 3;
int value = 1;
int square = input * input;
int direction = east;
int row = 0, column = 0;
int[] count = new int[]
{
input - 1,
input - 1,
0,
1
};
int[][] spiral = new int[input][];
for (int i = 0; i < input; i++)
{
spiral[i] = new int[input];
}
spiral[0][0] = 1;
while (value < square)
{
switch (direction)
{
case east:
if ((column + 1) > count[east])
{
count[east] = count[east] - 1;
direction = south;
}
else
{
column = column + 1;
value = value + 1;
spiral[row][column] = value;
}
break;
case south:
if ((row + 1) > count[south])
{
count[south] = count[south] - 1;
direction = west;
}
else
{
row = row + 1;
value = value + 1;
spiral[row][column] = value;
}
break;
case west:
if ((column - 1) < count[west])
{
count[west] = count[west] + 1;
direction = north;
}
else
{
column = column - 1;
value = value + 1;
spiral[row][column] = value;
}
break;
case north:
if ((row - 1) < count[north])
{
count[north] = count[north] + 1;
direction = east;
}
else
{
row = row - 1;
value = value + 1;
spiral[row][column] = value;
}
break;
}
}
return spiral;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment