Copy a row of values from a 1D array that represents a three dimensional grid

130 Views Asked by At

So I have a 1D array representing a 3D grid of numbers which represents the game world, I access individual entries (X,Y,Z) like so:

array[x + width * (y + height * z)]

Is there a way I can copy out an entire row (for instance, all the Z values for (1,1)) without looping (I'm already looping through every entry. I want to save performance by checking for empty rows (all 0s) and skipping processing them)? I'd rather not use a jagged array if possible.

1

There are 1 best solutions below

0
On

You must ensure your data elements are arranged linearly as rows in memory:

row|row|row... etc.

You can then use the same sort of array access arithmetic mentioned in your question, to determine your index range for that row, let's call the range n->m, then do a fast block copy for elements n->m as per the following:

  • memcpy - C/C++
  • Array.Copy - C#
  • Arrays.copyOfRange - Java, good for native types; loop copy may be better for objects.

each of which will take n and m-n as start and size parameters, respectively.

Most languages will have some sort of implementation of a block array copy which uses native code under the hood, i.e. which performs a native copy.