【问题标题】:How to get a direction on the same train line?如何在同一条火车线路上获得方向?
【发布时间】:2020-01-21 10:05:07
【问题描述】:

您能否帮助我逐步说明我需要在同一条火车线上找到方向的逻辑。已经拥有具有 Next 和 Previous 功能的公共火车线。

public IStation Next(IStation s)
{
    if (!_stations.Contains(s))
    {
        throw new ArgumentException();
    }
    var index = _stations.IndexOf(s);
    var isLast = index == _stations.Count -1;
    if (isLast)
    {
        return null;
    }
    return _stations[index + 1];
}

public IStation Previous(IStation s)
{
    if (!_stations.Contains(s))
    {
        throw new ArgumentException();
    }
    var index = _stations.IndexOf(s);
    var isFirst = index == 0;
    if (isFirst)
    {
        return null;
    }
    return _stations[index - 1];
}

还有我寻找方向的功能。

public string GetLineDirectiom(Station from, Station to, Line commonLine)
{
    bool fromNextTo = true;


    //to.Lines.Count();
    //to.ToString();
    var Final = commonLine.Next(from);
    while (Final != null)
    {

    }

    if (fromNextTo)
        return "next";
    else return "previous";
}

【问题讨论】:

  • Line commonLine 是什么?
  • 在检查 _stations.Contains 和 _stations.IndexOf 时,您会做双重工作。如果找不到站,IndexOf 将返回 -1。请修复它:)
  • @PavelAnikhouski:显然,Line 类的实例包含来自第一个代码块的 NextPrevious 方法。

标签: c# next directions


【解决方案1】:

您似乎正在尝试“访问沿commonLine 的车站”,从from 车站开始。

你开始的循环是一个有效的开始;您需要一个变量来存储您当前正在访问的电台。可能当前的变量名Final在这里让你自己有点迷惑,因为它不是线路的“终”站,只是你当前访问的那个站。

因此,我们将变量命名为currentStation。然后,你想去下一站,直到你找到to(从而知道方向),或者直到你到达终点:

var currentStation = from;
while (currentStation != null)
{
    if (currentStation == to)
    {
        return "next";
    }
    currentStation = commonLine.Next(currentStation);
}

现在,这将检查 to 是否“领先”。如果不是,您可以继续检查是否可以在另一个方向找到它,再次从from开始:

currentStation = from;
while (currentStation != null)
{
    if (currentStation == to)
    {
        return "previous";
    }
    currentStation = commonLine.Previous(currentStation);
}

如果这个循环也没有找到to,显然to 不在线上。根据您的喜好处理此案例。

一些备注:

  • 将方向指示为“下一个”或“上一个”可能有点误导。如果确实是行的方向,请考虑诸如“前进”和“后退”之类的内容,因为“下一个”和“上一个”确实暗示了列表中的直接下一个/上一个元素。
  • 虽然上述方法有效,但我确实注意到您的Line 对象已经在索引列表中包含了电台。因此,实现目标的一种更简单的方法可能是仅确定commonLine 上的fromto 站的索引,然后比较哪个大于另一个。

【讨论】:

    【解决方案2】:

    不清楚你想做什么以及为什么要返回字符串“next”和“prev”作为方向,但通常是通过两个站来获取方向:

        public int GetStationIndex(IStation s)
        {
            var index = _stations.IndexOf(s);
            if (index == -1)
            {
               throw new ArgumentException();
            }
    
            return index ;
        }
    
    
        public string GetLineDirection(Station from, Station to, Line commonLine)
        {
           var direction = commonLine.GetStationIndex(from)<commonLine.GetStationIndex(to)?"next" : "previous" 
           return direction;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多