0

Suppose I have something like this:

int[][] arr = new int[22][];
for (int i = 0; i < 22; ++i)
{
    arr[i] = new int[22];
}
for (int x = 0; x < 22; ++x)
{
    for (int y = 0; y < 22; ++y)
    {
        arr[x][y] = ...;
    }
}

I'm trying to flatten arr, but still being able to use x and y separately as indexes.

I was able to achieve this by creating a new 1d array with a size of ((21 << 5) | 21) + 1, because 21 uses 5 bits, and you can combine them like that.

You can then convert x and y into a single array index by doing: (x << 5) | y, and this works fine.

However, the issue is this is space inefficient. There are only 22 * 22 elements, but you have to create an array with size ((21 << 5) | 21) + 1. That is 484 vs 694 elements.

Is there any way to flatten arr but still being able to use x and y separately as indexes (and being space-efficient)?

  • How about just create an array of length 484, and use `y * 22 + x` or `x * 22 + y` to calculate the index? Do you not like multiplication for some reason? – Sweeper Jul 18 '21 at 02:44
  • The whole point of "flattening" an array is to make it 1-dimensional. If you want to be efficient, allocate the elements needed to hold all the items upfront. If you want to access items in the new flattened array using the old indexing scheme, you need to calculate the new indices into the new array. – Jeff Mercado Jul 18 '21 at 02:44
  • @Sweeper But how would you make it work for 3d jagged arrays? – NewUwpPerson Jul 18 '21 at 02:45
  • For a 22*22*22 array, `x * 22 * 22 + y * 22 + z`. Does it not work? – Sweeper Jul 18 '21 at 02:47
  • @Sweeper oops i'm a moron – NewUwpPerson Jul 18 '21 at 02:52
  • This doesn't answer your question, but you may get some ideas after checking out my answer to this question https://stackoverflow.com/questions/66324262/performant-concatenating-2d-arrays-stored-as-sub-arrays/66325673#66325673 – Flydog57 Jul 18 '21 at 03:49
  • But....... why? – Caius Jard Jul 18 '21 at 06:15

0 Answers0