从位置获取螺旋索引 [英] Get spiral index from location

查看:66
本文介绍了从位置获取螺旋索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Alberto Santini的解决方案来获得基于项目索引的螺旋网格参考

I'm using Alberto Santini's solution to this question to get a spiral grid reference based on an items index

从原点开始在离散的2D网格上迭代向外螺旋的算法

这不是公认的解决方案,但这是我最需要的解决方案,因为它避免使用循环.

It's not the accepted solution, but it's the best for my needs as it avoids using a loop.

它运作良好,但是我现在想要做的是相反的操作.根据已知的x和y坐标返回位置索引.

It's working well, but what I want now is to do the inverse. Based on a known x and y coordinate return the index of a location.

这是退还给定位置周围的物品的前提.

This is as a precursor to returning the items surrounding a given location.

推荐答案

邮政编码:

if y * y >= x * x then begin
  p := 4 * y * y - y - x;
  if y < x then
    p := p - 2 * (y - x)
end
else begin
  p := 4 * x * x - y - x;
  if y < x then
    p := p + 2 *(y - x)
end;

描述:左上半对角线(0-4-16-36-64)包含平方的层号(4 * layer ^ 2).外部if语句定义层并在左上半平面的相应行或列中找到位置的(预)结果,而内部if语句则为镜像位置校正结果.

Description: Left-upper semi-diagonal (0-4-16-36-64) contains squared layer number (4 * layer^2). External if-statement defines layer and finds (pre-)result for position in corresponding row or column of left-upper semi-plane, and internal if-statement corrects result for mirror position.

这篇关于从位置获取螺旋索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆