1
\$\begingroup\$

I have a grid, which the user can expand as he wishes. Since I don't know how big the grid will end up (and many tiles will stay empty) a two dimensional array (Tile[][] gird) wouldn't work. But I feel like just adding Tiles to a list (List<Tile> grid) can't be the best way, since when I want to get a Tile I have to search for it every time (grid.SingleOrDefault(t => t.x == _x && t.y == _y)). Which is ofcourse not ideal.

Is there a method which e.g. sorts the List<Tile> in a way that it's faster to accesss a given tile?

enter image description here

\$\endgroup\$
10
  • \$\begingroup\$ When you say "saving", do you mean serializing to a saved game file on disc? Or are you just looking for in-memory representations? \$\endgroup\$
    – DMGregory
    May 12 at 12:39
  • \$\begingroup\$ @DMGregory Just for memory. But at some point also for saving on a disk \$\endgroup\$ May 12 at 12:46
  • \$\begingroup\$ These will likely have two very different solutions: the in memory representation should be optimized for fast random access and ease of expanding. The on-disc representation doesn't need those features, but would benefit from compactness. So you'll probably want to ask about each problem separately. I'd recommend using keywords like "storing" "representing" or "data structure" for the in-memory case, rather than "saving" which suggests the serialize-to-disc case. \$\endgroup\$
    – DMGregory
    May 12 at 12:49
  • \$\begingroup\$ Maybe a dictionary? \$\endgroup\$
    – Mangata
    May 12 at 13:00
  • 1
    \$\begingroup\$ @Mangata remember that big-O notation tells you asymptotic complexity, meaning how the work scales as n gets larger. It does not let you compare the absolute costs for a fixed n. In practice, linearly searching an array can be faster than a dictionary lookup even for n values in the low thousands, depending on the details of the implementation/hardware etc. That's not to say dictionaries are bad, but the trade-off is not quite so "obvious" as the big-O analysis makes it seem. \$\endgroup\$
    – DMGregory
    May 12 at 16:44

0

You must log in to answer this question.

Browse other questions tagged .