Skip to content

Commit 49c601c

Browse files
Hilbert encode/decode 35% and 53% faster respectively
1 parent e7dfc18 commit 49c601c

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

numerics/hilbert/hilbert.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -44,29 +44,30 @@ func boolToInt(value bool) int32 {
4444
return int32(0)
4545
}
4646

47-
func rotate(n, rx, ry int32, x, y *int32) {
47+
func rotate(n, rx, ry int32, x, y int32) (int32, int32) {
4848
if ry == 0 {
4949
if rx == 1 {
50-
*x = n - 1 - *x
51-
*y = n - 1 - *y
50+
x = n - 1 - x
51+
y = n - 1 - y
5252
}
5353

54-
t := *x
55-
*x = *y
56-
*y = t
54+
t := x
55+
x = y
56+
y = t
5757
}
58+
return x, y
5859
}
5960

6061
// Encode will encode the provided x and y coordinates into a Hilbert
6162
// distance.
6263
func Encode(x, y int32) int64 {
6364
var rx, ry int32
6465
var d int64
65-
for s := int32(n / 2); s > 0; s /= 2 {
66+
for s := int32(n >> 1); s > 0; s = s >> 1 {
6667
rx = boolToInt(x&s > 0)
6768
ry = boolToInt(y&s > 0)
6869
d += int64(int64(s) * int64(s) * int64(((3 * rx) ^ ry)))
69-
rotate(s, rx, ry, &x, &y)
70+
x, y = rotate(s, rx, ry, x, y)
7071
}
7172

7273
return d
@@ -82,7 +83,7 @@ func Decode(h int64) (int32, int32) {
8283
for s := int64(1); s < int64(n); s *= 2 {
8384
rx = 1 & (t / 2)
8485
ry = 1 & (t ^ rx)
85-
rotate(int32(s), int32(rx), int32(ry), &x, &y)
86+
x, y = rotate(int32(s), int32(rx), int32(ry), x, y)
8687
x += int32(s * rx)
8788
y += int32(s * ry)
8889
t /= 4

0 commit comments

Comments
 (0)