You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含交替短列的六边形排列坐标数组转为锯齿形路径?

问题描述

开发圆排列程序时,需要为六边形排列的圆生成锯齿形(zig-zag)路径,其中每隔一列的元素数量少一个(偶列5个元素,奇列4个元素)。当前实现的路径未正确呈现锯齿形,前几列运行正常但后续出现混乱。

原代码如下:

def zigzag_positions(cols, rows, stored_seed_positions, y_diff):
    zigzag_positions = []
    s = 0

    for i in range(int(cols)):
        if i % 2 == 0:  # even cols
            for j in range(0 - s, int(rows), 1):
                index = i * int(rows) + j
                if index < len(stored_seed_positions):
                    zigzag_positions.append(stored_seed_positions[index])
        else:  # odd cols
            for j in range(int(rows)-2, -1, -1):
                index = i * int(rows) + j
                if index < len(stored_seed_positions):
                    zigzag_positions.append(stored_seed_positions[index])

            s += 1

    return zigzag_positions

正常路径数组示例:

[(102, 102), (102, 206), (102, 310), (102, 414), (102, 518), 
(193, 154), (193, 258), (193, 362), (193, 466), 
(285, 102), (285, 206), (285, 310), (285, 414), (285, 518), 
(376, 154), (376, 258), (376, 362), (376, 466), 
(468, 102), (468, 206), (468, 310), (468, 414), (468, 518), 
(559, 154), (559, 258), (559, 362), (559, 466)]

期望的锯齿形路径数组:

[(102, 102), (102, 206), (102, 310), (102, 414), (102, 518), 
(193, 466), (193, 362), (193, 258), (193, 154),
(285, 102), (285, 206), (285, 310), (285, 414), (285, 518), 
(376, 466), (376, 362), (376, 258), (376, 154),
(468, 102), (468, 206), (468, 310), (468, 414), (468, 518), 
(559, 466), (559, 362), (559, 258), (559, 154)]
解决方案

原代码核心问题是索引计算逻辑错误:奇偶列元素数量不同(偶列rows个,奇列rows-1个),但代码用i * int(rows)计算列起始索引,导致奇列索引偏移错误,后续列元素选取混乱。

修改思路:

  1. 用变量动态跟踪每一列的实际起始索引,累加前面所有列的元素数量;
  2. 偶列直接正序取对应范围内的元素;
  3. 奇列倒序取对应范围内的元素。

修改后的代码:

def zigzag_positions(cols, rows, stored_seed_positions, y_diff):
    zigzag_positions = []
    current_start = 0  # 记录当前列的起始索引

    cols = int(cols)
    rows = int(rows)

    for i in range(cols):
        if i % 2 == 0:
            # 偶列:取rows个元素,正序添加
            end = current_start + rows
            zigzag_positions.extend(stored_seed_positions[current_start:end])
            current_start = end
        else:
            # 奇列:取rows-1个元素,倒序添加
            end = current_start + (rows - 1)
            zigzag_positions.extend(reversed(stored_seed_positions[current_start:end]))
            current_start = end

    return zigzag_positions

关键修改点:

  • 移除了原代码中逻辑混乱的s变量,改用current_start动态跟踪列起始索引;
  • 偶列直接切片取对应数量元素并正序添加;
  • 奇列切片取对应数量元素后反转,实现倒序添加;
  • 简化索引计算逻辑,避免因列元素数量差异导致的索引偏移问题。

测试该代码后,生成的路径将完全匹配期望的锯齿形效果。

内容的提问来源于stack exchange,提问作者Yasser Machkour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:53:17