gpt4 book ai didi

java - 根据Board数据结构Cell[][]中的编号获取Cell,无需经过2个FOR循环

转载 作者:行者123 更新时间:2023-12-02 05:37:31 24 4
gpt4 key购买 nike

我需要创建由细胞组成的棋盘游戏。电路板应该是 5X5 ==> 25 个单元我想知道使用什么数据结构:Cell[][] (“矩阵”)或ArrayList<Cell> .
我选择Cell[][] ,Java 中的二维数组(“矩阵”)的 Cells。

每个单元格都有编号。这就是它在矩阵中的样子: enter image description here

例如:

matrix[0][2] = Cell number 3  
matrix[2][4] = Cell number 15
matrix[3][3] = Cell number 19

我在如何根据 Cell 的编号获取 Cell 时遇到问题。

例如,如果我想获取单元格号 19,我需要通过两个 FOR 循环传递所有行和所有列。在 ArrayList 中更容易,只需使用 'get(int index)' 函数即可。

当我使用Cell[][]的数据结构时,有没有更好的方法根据单元格的编号获取单元格?
我想在构建单元格时获得单元格的行号和列号:

public class Cell   
{
private int m_RowNum;
private int m_ColNum;
private int m_Number;
}

但不知道该怎么做。
也许我可以构建一些无需传递两个 FOR 循环即可获取 Cell 的函数?

最佳答案

您只需要一个公式即可将单元格编号转换为其关联的二维坐标:

row = floor((number - 1) / columns);
column = (number - 1) % columns;

例如,对于单元格号 1,您将得到:

row = floor((1 - 1) / 5) = 0 
column = (1 - 1) % 5 = 0;

这意味着单元格号 1 位于 (0, 0)

对于单元格号 2,您将得到:

row = floor((2 - 1) / 5) = 0
column = (2 - 1) % 5 = 1

这意味着单元格号 2 位于 (0, 1)

让我们选择一个重要的,例如17。你得到:

row = floor((17 - 1) / 5) = floor(16 / 5) = 3
column = (17 - 1) % 5 = 16 % 5 = 1

这意味着单元格编号 17 位于 (3, 1)

关于java - 根据Board数据结构Cell[][]中的编号获取Cell,无需经过2个FOR循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24831874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com