繁体   English   中英

位置层次结构数据结构

[英]Location hierarchy data structure

位置层次结构的数据结构或数据模型

I have the following location types,

Airport
City
State
Country

Hierarchy is Country has a state, State has a City and a City has airport.

City:San Francisco To City:Frankfort    Rate is 100$ is stored in the system in some form.

当有人要求从Airport:SFO到Airport:FRA的价格时,应用程序应查找从Airport:SFO到Airport:FRA的任何可用价格。

由于我们没有人(我们只有城市到城市),因此应用程序应检查到机场的更高一级,即城市。 因此,应用程序应该能够找到“机场:SFO”和“机场:法兰克福”城市,并检查房价是否可用。 在这种情况下,由于City:San Francisco到City:Frankfort的费率保持为100 $,因此它将收取100 $。

如何在数据结构中表示此位置层次结构(在Java中)? 图形或树会有用吗? 如果可以,请提供一些样品。

IMO,有两种自下而上或自上而下的方式(尽管两者实际上都是基于HAS-A关系的:

自下而上:

1,有班级机场,城市,州,国家

2,机场有城市,城市有州,州有国家变量

现在,无论何时需要费率,都可以转到机场对象,检查城市->州->国家等,并相应收费

自顶向下:

1,有国家,州,城市,机场班

2,国家/地区将具有包含州/省的清单,州/省将具有城市的清单,城市将具有机场的清单

我更喜欢第一个,因为维持1的父母价值比维持所有孩子的名单更容易/有效。

您可以尝试以下树状结构

好处

1.跨不同位置类型的统一数据结构。

2.在添加新的位置类型的情况下,无需新的班级。

3.parent查找变得容易。

4.父递归遍历成为可能。

5.递归遍历孩子成为可能。

public class Location
{
    private LocationType locationType;
    private Set<Location> children = new HashSet<Location>();
    private Location parent;

    public int rateTo(Location location)
    {
        int rate = -1;

        Location from = this;
        Location to = location;

        do
        {
            rate = getRate(from, to);
            if (rate > -1)
                break;

            from = from.parent;
            to = to.parent;

            if (from == null || to == null)
                break;
        } while (true);

        return rate;
    }

    public void addChildLocation(Location child)
    {
        child.parent = this;
        children.add(child);
    }

    public int getRate(Location from, Location to)
    {
        //1. implement your own database lookup, etc......
        //2. take care of reverse location parameters also...
        return -1;
    }

    public enum LocationType
    {
        Airport,
        City,
        State,
        Country
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM