Skip to content

Instantly share code, notes, and snippets.

@Trinitek
Created December 4, 2017 19:17
Show Gist options
  • Select an option

  • Save Trinitek/9dcf8500151f855d297fdf7f163c0374 to your computer and use it in GitHub Desktop.

Select an option

Save Trinitek/9dcf8500151f855d297fdf7f163c0374 to your computer and use it in GitHub Desktop.
Advent of Code 2017 Day 3
using System;
namespace AdventOfCode2017
{
public static class Day3
{
public static string GetSolution()
{
int input = 277678;
return CountSteps(input).ToString();
}
public static int CountSteps(int cell)
{
if (cell == 1)
{
return 0;
}
int a;
int b;
int c;
int d = 1;
int dPrev;
int ring;
int steps = 0;
for (ring = 1; ; ring++)
{
dPrev = d;
(a, b, c, d) = CalculateRingValues(ring);
if (a >= cell ||
b >= cell ||
c >= cell ||
d >= cell)
{
break;
}
}
int Center(int x, int y) => (x + y) / 2;
int Delta(int center) => Math.Abs(center - cell);
int OuterSteps(int x, int y) => Delta(Center(x, y));
if (cell <= a)
{
steps = OuterSteps(a, dPrev);
}
else if (cell <= b)
{
steps = OuterSteps(b, a);
}
else if (cell <= c)
{
steps = OuterSteps(c, b);
}
else if (cell <= d)
{
steps = OuterSteps(d, c);
}
steps += ring;
return steps;
}
public static (int a, int b, int c, int d) CalculateRingValues(int ring)
{
if (ring <= 0)
{
throw new ArgumentOutOfRangeException(nameof(ring));
}
// Corner values, set to their initial ring 1 values
int a = 3;
int b = 5;
int c = 7;
int d = 9;
// Number of steps added with each additional ring
const int increment = 2;
for (int baseRing = 1; baseRing < ring; baseRing++)
{
int RoundTrip(int baseRingSteps, int destRingSteps)
{
return
(increment * (baseRing) * baseRingSteps) +
(increment * (baseRing + 1) * destRingSteps);
}
a += RoundTrip(3, 1);
b += RoundTrip(2, 2);
c += RoundTrip(1, 3);
d += RoundTrip(0, 4);
}
return (a, b, c, d);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment