Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

5 of 7
added more details about g
Arnauld
  • 205.5k
  • 21
  • 187
  • 670

JavaScript (ES6), 136 bytes

Expects (p)(q) and returns \$p\lozenge q\$.

p=>q=>((g=(t,h=o=[1],v=n=x=y=0)=>n-t|x-t[0]|y-t[1]?g(t,...o[o[[x-=h,y-=v]]=++n,[x-v,y+h]]?[h,v]:[v,-h]):x)(q),Y=2*y,g([2*x-g(p),Y-y]),n)

Try it online!

How?

The helper function \$g\$ expects a target \$t\$ which is either the index or the coordinates of an element in the spiral.

The test on \$t\$ is pretty simple:

n - t | x - t[0] | y - t[1]
  • If \$t\$ is an integer, both x - t[0] and y - t[1] are NaN, so only n - t is taken into account.
  • If \$t\$ is an array, n - t is NaN and only x - t[0] | y - t[1] is taken into account.

Whenever \$g\$ is called, it starts at the origin and walks through the spiral until the target is reached, keeping track of its index \$n\$ and its position \$(x,y)\$ (all these variables being available in the global scope).

We first invoke \$g(q)\$ to get the coordinates \$(X,Y)\$ of the 2nd element, then \$g(p)\$ to get the coordinates \$(x,y)\$ of the 1st element, and finally \$g([2X-x,2Y-y])\$ to get the index of \$p\lozenge q\$.

Arnauld
  • 205.5k
  • 21
  • 187
  • 670

AltStyle によって変換されたページ (->オリジナル) /