From 8cb53d40617c7c66cfe4cb0572c64215c2195d3e Mon Sep 17 00:00:00 2001 From: Andrew Coleman Date: Mon, 4 Dec 2017 00:02:10 -0500 Subject: [PATCH] day3 solution --- day3/Makefile | 8 ++++++++ day3/day3.erl | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 day3/Makefile create mode 100644 day3/day3.erl diff --git a/day3/Makefile b/day3/Makefile new file mode 100644 index 0000000..ece3ad8 --- /dev/null +++ b/day3/Makefile @@ -0,0 +1,8 @@ +all: day3.beam + erl -noshell -s day3 start -s init stop + +day3.beam: + erlc day3.erl + +clean: + rm -f day3.beam diff --git a/day3/day3.erl b/day3/day3.erl new file mode 100644 index 0000000..021b0a0 --- /dev/null +++ b/day3/day3.erl @@ -0,0 +1,42 @@ +-module(day3). +-export([start/0]). + +next_largest_square(Target) + -> recurse_next_largest_square(1, Target). + +recurse_next_largest_square(X, Target) + when (X rem 2) =/= 0, (X*X) >= Target -> X; +recurse_next_largest_square(X, Target) + -> recurse_next_largest_square(X+1, Target). + +position_in_outer_shell(Square, Target) + -> PreviousSquare = (Square - 2) * (Square - 2), + Target - PreviousSquare. + +position_on_side(Position, Square) + when Position == 0 -> Square - 1; +position_on_side(_Position, Square) + when Square == 1 -> 1; +position_on_side(Position, Square) + -> Offset = Position rem (Square - 1), + if Offset == 0 -> Square - 1; + true -> Offset end. + +distance_to_center(Position, Square) + -> Center = Square div 2, + VertOffset = abs(Center - Position), + Center + VertOffset. + +find_distance(Target) + -> Square = next_largest_square(Target), + Position = position_in_outer_shell(Square, Target), + Index = position_on_side(Position, Square), + distance_to_center(Index, Square). + +start() + -> io:fwrite("~B ~B~n", [1, find_distance(1)]), + io:fwrite("~B ~B~n", [12, find_distance(12)]), + io:fwrite("~B ~B~n", [23, find_distance(23)]), + io:fwrite("~B ~B~n", [1024, find_distance(1024)]), + io:fwrite("~B ~B~n", [368078, find_distance(368078)]), + io:fwrite("https://oeis.org/A141481/b141481.txt~n").