python - 给定一个 N 边方阵,有没有办法在不使用循环或 if 条件的情况下找到单元格的环值?

标签 python matrix computational-geometry

例如,假设您有一个 6 边的方阵。 这些是单元格笛卡尔索引:

(0,0) (0,1) (0,2) (0,3) (0,4) (0,5)
(1,0) (1,1) (1,2) (1,3) (1,4) (1,5)
(2,0) (2,1) (2,2) (2,3) (2,4) (2,5)
(3,0) (3,1) (3,2) (3,3) (3,4) (3,5)
(4,0) (4,1) (4,2) (4,3) (4,4) (4,5)
(5,0) (5,1) (5,2) (5,3) (5,4) (5,5)

一个 6 边正方形有 3 个环:a

A A A A A A
A B B B B A
A B C C B A
A B C C B A
A B B B B A
A A A A A A

问题:获取单元格坐标、正方形边 N 并相应地返回环值的函数是什么?例如:

f(x = 1, y  2, N = 6) = B

A,B,C... 可以是任何数值:1,2,3 ... 或 0,1,2 ... 或其他任何值。重要的是它们对于任何 N 都是全等的。例如:

N = 1   =>   A = 1
N = 2   =>   A = 1
N = 3   =>   A = 1, B = 2
N = 4   =>   A = 1, B = 2
N = 5   =>   A = 1, B = 2, C = 3
N = 6   =>   A = 1, B = 2, C = 3
N = 7   =>   A = 1, B = 2, C = 4, D = 4
...

使用if条件问题很容易解决。 给定一对 (x,y) 和正方形边 N:

# N//2 is the number of rings in a N-side square
for k in range(1,N//2+1):
    if x == 0+k-1 or y== 0+k-1 or x == N-k or y == N-1:
        return k

不过,这似乎是一种非常昂贵的查找单元格环值的方法。 我一直在尝试使用单元格的对角线、坐标总和、坐标差...来查找函数,但我仍然找不到任何东西。 有没有人遇到过这个问题? 有办法解决吗?

最佳答案

看起来像是要解决的数学问题。 编辑:更新的功能,我希望能够更好地处理中点之后的偶数和奇数情况。但是,OP 要求将其转化为数学方程式,我不确定该怎么做。

import math


def ring_finder(x, y, N, outer_ring = 0):
    '''
    x and y are the coordinates of a cell, N is the length of the side of square
    Returns the correct ring count starting from outer_ring value (default, 0)
    '''
    if x >= N or y >= N:
        print("coordinates outside square, please check")
        return None
    no_of_squares = math.ceil(N/2)
    x = N - x - 1 if x >= no_of_squares else x
    y = N - y - 1 if y >= no_of_squares else y
    return min(x, y) + outer_ring

取环器(5, 5, 6)

ring_finder(1, 2, 6)

关于python - 给定一个 N 边方阵,有没有办法在不使用循环或 if 条件的情况下找到单元格的环值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55497695/

相关文章:

Python类: How to check whether an attribute is defined inside __init__ or outside __init__

python - 构建分配矩阵 - Python

python - Opencv是否允许您使用6点来计算3x4透视变换?

python - Kivy:从 python 代码更改屏幕

python - 应用Sklearn高斯混合算法拟合GM曲线

python - Birdsong 音频分析 - 找出两个剪辑的匹配程度

performance - 在 Matlab 中不使用 for 循环操作矩阵

python - 二维矩阵 : Finding and deleting columns that are subsets of other columns

geometry - 移动两个多边形以便它们接触边缘的距离

algorithm - 最近的点到点,最近的点到线