1

I'm developing a 2D map editor for a game and I need a way to increase or decrease the size of the grid/map uniformly in all directions.

Suppose you have a 3x3 map with a sort of "cross" symbol.

(arrays are zero-indexed. They start with 0)

Like this:

0,1,0
1,1,1
0,1,0

The array would look like this:

map = [0,1,0,1,1,1,0,1,0]

So, tile index 4 would be the center of the map.

I'd like to increase the size from 3x3 to 5x5 for example. So I end up with this:

0,0,0,0,0
0,0,1,0,0
0,1,1,1,0
0,0,1,0,0
0,0,0,0,0

The new map array should end up like this:

map = [0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0]

What's a good way of doing this?

Petter Thowsen
  • 1,697
  • 1
  • 19
  • 24

1 Answers1

1

Here are two functions for increase and decrease. The parameter arr is your one-dimensional map and xWidth is the width (and of course the height) of your grid. I had a question with a similar background here on Stackoverflow so many thanks to willywonka_dailyblah who helped me on the j and i indices.

public int[] increase_grid(int[] arr, int xWidth)
{
  int newWidth = (xWidth+2);
  int[] result = new int[newWidth * newWidth];
  int count=0;
  while(count<newWidth)
  {
     result[count++] = 0; 
  }

  for (int i=0;i<xWidth;i++)
  {  
      result[count++] = 0; 
      for (int j=0;j<xWidth;j++)
      {
         result[count++] = arr[i * xWidth + j];
      }
      result[count++] = 0; 
  }
  while(count<(newWidth*newWidth))
  {
     result[count++] = 0; 
  }

  return result;
}


public int[] decrease_grid(int[] arr, int xWidth)
{
    int newWidth = (xWidth-2);
    int[] result = new int[newWidth*newWidth];

    for(int i=0; i< newWidth;i++)
    {
       for (int j=0;j< newWidth;j++)
       {
           result[i* newWidth + j] = arr[(i+1) * xWidth + (j+1)];
       }
    }

    return result;
}

And I have this print function:

public void print_arr(int[] a, int xWidth)
{
   for(int i=0;i<xWidth;i++)
   {
      for(int j=0;j<xWidth;j++)
      {
         System.out.print(a[i * xWidth + j]+" "); 
      }
      System.out.println();
   }
   System.out.println();
}

You call these functions like:

  int[] map = new int[]{0,1,0,1,1,1,0,1,0};
  print_arr(map, 3);
  map = increase_grid(map, 3);
  print_arr(map, 5);

  map = increase_grid(map, 5);
  print_arr(map, 7);

  map = decrease_grid(map, 7);
  print_arr(map, 5);

So you have to pass the current size of your map and either call increase or decrease. Beware, that the these functions include a nested for-loop. Thus, they are less scale-able on greater grid sizes. I think there may be a solution to wrap even this into a loop-sequence, which runs without nesting.

Community
  • 1
  • 1
Jankapunkt
  • 8,128
  • 4
  • 30
  • 59