Skip to content

Instantly share code, notes, and snippets.

@tom-galvin
Created August 10, 2015 13:09
Show Gist options
  • Save tom-galvin/be44d9f52a288c0c0ac9 to your computer and use it in GitHub Desktop.
Save tom-galvin/be44d9f52a288c0c0ac9 to your computer and use it in GitHub Desktop.
DailyProgrammer Challenge #227e Solution (Square Spirals)
using System;
using System.Linq;
namespace ChallengeSpiral
{
class Program
{
static long ToPoint(long x, long y, long s)
{
if(x <= y)
{
if(x <= s - y + 1)
{
long p = s + 1 - 2 * x;
return p * p + 1 + y - x;
} else
{
long p = 2 * y - s;
return p * p + x - y;
}
}
else
{
if (x <= s - y + 1)
{
long p = s + 1 - 2 * y;
return p * p + y + 1 - x;
}
else
{
long p = 2 * x - s - 2;
return p * p + x - y;
}
}
}
static Tuple<long, long> ToLocation(long p, long s)
{
long sq = (long)Math.Ceiling(Math.Sqrt(p));
long offset = p - sq * sq + 2 * sq - 2, center = (s + 1) / 2;
long parity = (1 - (sq % 2) * 2);
return new Tuple<long, long>(
(sq / 2 - Math.Max(0, offset - sq + 1)) * parity + center,
((sq - 1) / 2 - Math.Min(offset, sq - 1)) * parity + center);
}
static void Main(string[] args)
{
Console.Write("Grid size: ");
long gridSize = Convert.ToInt64(Console.ReadLine());
if (gridSize % 2 == 1)
{
Console.WriteLine("Grid size must be even.");
}
else
{
Console.Write("Input: ");
long[] inputs = Console.ReadLine().Split(' ').Select(s => Convert.ToInt64(s)).ToArray();
if (inputs.Length == 1) // Point to location
{
var location = ToLocation(inputs[0], gridSize);
Console.WriteLine("Location of Point {0} is ({1}, {2}).",
inputs[0],
location.Item1, location.Item2);
}
else if (inputs.Length == 2) // location to Point
{
Console.WriteLine("Point corresponding to location ({0}, {1}) is {2}.",
inputs[0], inputs[1],
ToPoint(inputs[0], inputs[1], gridSize));
}
else
{
Console.WriteLine("Malformed input.");
}
Console.ReadKey();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment