c# - 给定一个网格中的位置,它是什么行和列

标签 c# math graph matrix

我有一个正在编写的应用程序,我必须在其中将街道地址放在预定义的标签纸上。此标签页有 3 列和 10 行。我有正确创建标签的循环,但需要允许用户能够选择工作表上的哪个标签开始。我原以为这将是一个简单的数学矩阵方程,但我无法想出或找到解决方案。

这是一个例子:

1   2  3  4  5
6   7  8  9 10
11 12 13 14 15 

鉴于上面的矩阵,假设用户决定从#6 开始。我需要能够告诉我的循环从该位置开始:col:1 row:2。

如果有帮助,我的循环看起来像这样,但我认为这归结为我没有想到的数学方程式:

for (var yCounter = 0; yCounter < _labelSettings.LabelPerColumn; yCounter++)
{
    for (var xCounter = 0; xCounter < _labelSettings.ColumnsPerPage; xCounter++)
    {       
        foreach (var table in customNugget.PdfTables)
        {
            table.YPosition = SheetSettings.PageHeight -
                              (verticalOffset + yCounter * ((verticalSize + verticalOffset)));

            table.XPosition = horizontalOffset + xCounter * ((horizontalSize + horizontalOffset));
        }
    }
}

编辑

     private static int _cellsPerRow = 3;
    private static int _startIndex;

    static void Main(string[] args)
    {

        string userInput = Console.ReadLine();
        _startIndex = int.Parse(userInput);

        int startY = _startIndex / _cellsPerRow;
        int startX = (_startIndex - 1) % _cellsPerRow;

        Console.WriteLine(string.Format("The index you chose lives in the following matrix location:\n Row: {0} Column: {1}", startY, startX));
        Console.WriteLine("Press any key to continue...");
        Console.Read();

    }

最佳答案

假设您知道每行中的单元格数(我认为应该是 _labelSettings.ColumnsPerPage),您可以像这样计算起始值:

int cells = 5;//number of cells per row
int startAt = 6;//cell number to start at

int startY = (startAt - 1) / cells;//1
int startX = (startAt - 1) % cells;//0

然后您可以使用这些起始值来初始化您的循环,但是您需要小心确保您的内部循环仅在第一次运行时使用计算出的起始值。为此,您可以在第一次执行 y 循环后重置 startX。像这样:

for (var yCounter = startY; yCounter < _labelSettings.LabelPerColumn; yCounter++)
{
    for (var xCounter = startX; xCounter < _labelSettings.ColumnsPerPage; xCounter++)
    {
        //do stuff
    }
    startX = 0;//reset so that the next execution starts at the beginning of the row
}

Here is proof of the logic, though it is in javascript

编辑:startY 的计算已被修改以正确处理从最后一个数字开始的一行(感谢@Zach 指出错误)

关于c# - 给定一个网格中的位置,它是什么行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19730675/

相关文章:

c - 如何在两个节点之间的循环图中找到最长路径?

java - 使用 BouncyCaSTLe 签署消息摘要

c# - iOS TableView 按钮被多次调用

c# - SQL Server - 注册在尝试完成事务时要运行的用户代码

c# - 使用 .NET Core 的硬件内在函数将 64 位整数相乘

c# - 如何将已排序的整数列表重新排序为批处理,以便每个批处理的整数彼此之间的距离尽可能远?

c# - 使用单声道在 pi 上托管 asp.net owin 网页导致主机错误

algorithm - 一小部分输入的比较排序下限?

ios - 在 iOS 中绘制气泡图?

algorithm - 位于半圆内的点的 MST 上界