Search code examples
c#graphhashmaphashtable

Using x and y coordinates as a Hashtable key?


I am working through Leetcode questions and a common scenario I am running into is where I have a solution I could use but it requires a hashtable to have the Key as a pair of X and Y coordinates. In googling this I am unable to find any help which makes me believe I am doing something wrong if I want to use them this way.

This commonly occurs in Graph questions or multidimensional array questions.

Does anyone have any thoughts on how I should be implementing this on a regular basis? Or any reasons why I SHOULDNT be doing this?

The language I am using for this is C# but I'm sure it applies to most languages.

Thanks a lot!


Solution

  • You could use a Tuple:

    var dict = new Dictionary<(int x, int y), string>();
    dict.Add((12, 34), "My Town");
    

    See related answer.

    Assuming that the coordinates are always smaller than MAX, you could calculate a combined key

    x * MAX + y