gpt4 book ai didi

language-agnostic - 如何从行和列计算索引?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:22 24 4
gpt4 key购买 nike

我想为任何给定的行和列计算一个索引(基数为 0),其中行和列的基数为 1 并且列数已知,例如2

如果 max_columns 为 2 且 index 为 5,则根据索引计算行号:

Row = (index % max_columns) + (int)(index / max_columns)
= (5 % 2) + (int)(5 / 2)
= 1 + 2
= 3

根据索引计算列数

Col = max_columns - (index % max_columns)
= 2 - (5 % 2)
= 2 - 1
= 1

问题是如何从索引以0为基数的任何索引计算行和列。这是在java应用程序中计算数组的索引。

'Willem Van Onsem' 为我提供的正确解决方案:

其中 Row 为 3,Col 为 2,max_columns 为 2:

Index = (Row * max_columns) + Col - max_columns - 1
= (3 * 2) + 2 - 2 - 1
= 6 + (-1)
= 5

最佳答案

给定每一行由 n 列组成,列和行的从零开始的索引是:

int row = index/n;
int col = index%n;

现在,由于您的 rowcol 偏移了 1,您只需将 1 添加到两者:

int row1 = (index/n)+1;
int col1 = (index%n)+1;

对于反函数,如果rowcol偏移0,您可以计算索引为:

int index = row*n+col;

或者如果索引偏移1:

int index = row1*n+col1-n-1;

关于language-agnostic - 如何从行和列计算索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35748843/

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