c# - 阵列阵列之间的距离

标签 c# arrays algorithm matrix multidimensional-array

我有以下场景:

public class World{
  public City[,] cities { get; set; }
}


public class City
{
    public int number_city { get; set; }        
    public int x { get; set; }
    public int y { get; set; }
    public World world { get; set; }
    public Slot[,] slots { get; set; }
}

public class Slot
{
    public City city { get; set; }

    public int x { get; set; }
    public int y { get; set; }
}

也就是说,它的功能是象棋场,我有一个对象世界有几个城市,每个城市都有一些插槽。每个城市的slots都排成一个网格,每个城市的网格有相同的行数和列数。

用这个方法我可以得到同一个城市的Slots之间的距离:

public static double GetDistance(int x0, int y0, int x1, int y1)
{
    int dX = y1 - y0;
    int dY = x1 - x0;
    return Math.Sqrt(dX * dX + dY * dY);
}

只有我需要获取不同城市的slots之间的距离

在每个城市中,时隙的位置从零开始,所以我不能直接使用它们来计算城市之间。

世界之间不需要距离。

世界(一个世界有几个城市)

Worlds

城市和时段

City and slot

例如,我需要黄色 PC 之间的距离,结果为 7

最佳答案

根据您在评论中发表的澄清,我编辑了您的问题以更好地反射(reflect)场景。您有 City 对象占据了 World。每个 CityWorld 中都有一个 X/Y 坐标,并且包含在 City< 中具有 X/Y 坐标的 Slot 对象。每个 City 的大小都相同,即具有相同的行数和列数,并且在世界范围内每个 City 都与其邻居完全相邻。 IE。没有差距,没有重叠,没有奇怪大小的城市等。

鉴于此,一旦您将问题视为简单的参照系问题,您的问题就很容易解决。也就是说,虽然 Slot 坐标相对于包含 SlotCity,但它们仍然存在于 World。借用物理学或计算机图形学中的一个概念,它们都有“参照系”,其中一个参照系中的坐标可以通过简单的变换映射到另一个参照系,我们可以将这个概念应用于您的问题。

特别是,您可以将 Slot 的 X/Y 坐标从 City 引用系转换为 World 引用系只需将 City X/Y 坐标乘以单个城市的宽度和高度,然后加上 Slot X/Y 坐标:

struct SlotPoint
{
    public readonly int X;
    public readonly int Y;

    public SlotPoint(int x, int y)
    {
        X = x; Y = y;
    }
}

const int _kcityWidth = 7;
const int _kcityHeight = 7;

SlotPoint ConvertCityToWorld(Slot slot)
{
    return new SlotPoint(
        slot.city.x * _kcityWidth + slot.x, slot.city.y * _kcityHeight + slot.y);
}

有了这个转换,计算任意两个槽之间的距离就很简单了:

double GetDistance(Slot slot1, Slot slot2)
{
    SlotPoint point1 = ConvertCityToWorld(slot1), point2 = ConvertCityToWorld(slot2);

    return GetDistance(point1.X, point1.Y, point2.X, point2.Y);
}

关于c# - 阵列阵列之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42613843/

相关文章:

c# - 字符串列表的排列算法

java - 可见范围项目/模块

c# - 如何将对象属性传递给报告(RDLC)C#

c# - 将二维数组转换为位图图像。 C#

algorithm - 可微函数的大 O 证明

c++ - <algorithm> 中的 "sort"函数可以用于对二维字符数组进行排序吗?

c# - 从 C# 中的未知长度流计算散列

C# - 从 SetWindowText 获取事件

VB.Net 动态初始化数组

javascript - 如何将包含对象字符串的数组转换为常规键对象对?