18
Given a Gaussian integer \$a+bi\$ where \$a\$,\$b\$ are integers and \$i = \exp\left(\pi i/2\right)\$ is the imaginary unit, return the closest (w.r.t to the Euclidean distance) Eisenstein integer \$k+l\omega\$ where \$k\$,\$l\$ are integers and \$\omega = \exp(2\pi i/3) = (-1+i\sqrt{3})/2\$.
Background
It is probably quite obvious that every Gaussian integer can uniquely be written as \$a+bi\$ with \$a\$,\$b\$ integers. It is not so obvious but nonetheless true: Any Eisenstein integer can uniquely be written as \$k+l\omega\$ with \$k\$,\$l\$ integers. They both form a \$\mathbb{Z}\$-module within the complex numbers, and are both p-th cyclotomic integers for \$p=2\$ or \$3\$ respectively. Note that \$3+2i \neq 3+2\omega\$
Source: commons.wikimedia.org
Details
In case the given complex number has two or three closest points, any of those can be returned.
The complex number is given in rectangular coordinates (basis \$(1,i)\$), but other than that in any convenient format like
(A,B)
orA+Bi
orA+B*1j
etc.- The Eisenstein integer has to be returned as coordinates of the basis \$(1,\omega)\$ but other than that in any convenient format like
(K,L)
orK+Lω
orK+L*1ω
etc.
Examples
All real integers should obviously be mapped to the real integers again.
6,14 -> 14,16
7,16 -> 16,18
-18,-2 ->-19,-2
-2, 2 -> -1, 2
-1, 3 -> 1, 4
Nice, I don't remember seeing a hexagonal grid since http://codegolf.stackexchange.com/q/70017/17602
– Neil – 2016-08-07T20:22:24.480Related – Lynn – 2016-08-07T20:37:53.783
@Neil There have been three others since then. ;)
– Martin Ender – 2016-08-07T20:48:34.063You should also include test cases when a and b have opposite signs. – SmileAndNod – 2019-08-05T10:10:21.517
@SmileAndNod Added one. But one could also just use the symmetry with respect to the real axis and just replace
(1,w)
with(-1,1+w)
. And I also renamed this section to Examples to make it clear that it is not sufficient to just provide the right results for these cases. – flawr – 2019-08-05T12:13:10.907@flawr It's an interesting puzzle for highlighting the difference between the floor function and the int function. – SmileAndNod – 2019-08-06T10:58:10.697
Suggested testcase:
– Bubbler – 2020-01-16T08:30:55.833-1, 3 -> 1, 4
. Some solutions (e.g. this and this) give the wrong answer1, 3
or0, 3
.@Bubbler Added! – flawr – 2020-01-17T22:01:39.347