I have a distance table, which I want to represent as code. It stores the distances between points and has same row and column headings. An upper right part of the table is a mirrored part of the lower left. And there are empty cells at intersections of the same points. How should I represent these in code so I could be able to get/set distance values by row and column ids without duplicating the values?
You can utilise Dictionary with two towns as a key.
Wrap it within class to hide implementation details and expose one method where you can check for a towns in any orders, which gives possibility to have dictionary without duplicates.
public class Distances
{
private readonly Dictionary<(string, string), int> _distances;
public Distances()
{
_distances = new Dictionary<(string, string), int>
{
{ ("Eilat", "Ashkelton"), 307 }
};
}
public int? FindBetween(string town1, string town2)
{
if (_distances.TryGetValue((town1, town2), out var distance1))
{
return distance1;
}
if (_distances.TryGetValue((town2, town1), out var distance2))
{
return distance2;
}
return null;
}
}
Usage
var distances = new Distances();
var distance = distances.FindBetween("Eilat", "Ashkelton"); // 307