Problem Statement
A spiral function maps a nonnegative integer n
onto integer coordinates (x, y)
in a spiral pattern on a Cartesian plane. The spiral starts at the origin (0, 0)
with n = 0
and expands outward in a counter-clockwise direction.
Write a function spiralCoordinates(n)
that takes an integer n
and returns its coordinates (x, y)
in the spiral.
Examples
Input: n = 1
Output: (0, 1)
Input: n = 3
Output: (-1, 0)
Input: n = 6
Output: (-1, -1)
Challenge I
Your function should run faster than linear time.
Challenge II
Can you also solve the inverse problem: given (x, y)
, determine n
?
I didn't expect this problem to hide such a nice arithmetic sum. My approach is fundamentally similar to Kyle's, but takes a different approach to the proof, so I'll write my solution in the reply to this comment. I didn't make a full implementation (might come back to that later), but this should be implementable in just a few lines of code.
Edit: Added implementation to below comment if anybody is interested
Definitely a great problem! It invokes good use of pattern analysis and mathematical thinking. I will write my solutions for both problems in reply to this comment.
--Do not look if you are still solving--