0

I have a 4x4 grid stored as a one-dimensional array, each cell can contain a random number:

var g1 = [
  1, 0, 0, 0,
  0, 2, 0, 0,
  0, 0, 0, 3,
  0, 0, 1, 0
];

How can I increase the resolution of that grid to get this 8x8 grid as an array:

var g2 = [
  1, 1, 0, 0, 0, 0, 0, 0,
  1, 1, 0, 0, 0, 0, 0, 0,
  0, 0, 2, 2, 0, 0, 0, 0,
  0, 0, 2, 2, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 3, 3,
  0, 0, 0, 0, 0, 0, 3, 3,
  0, 0, 0, 0, 1, 1, 0, 0,
  0, 0, 0, 0, 1, 1, 0, 0
];

The source array will be of different sizes, but the increase in resolution (1 to 4) will be the same. What's the most efficient way to calculate the indices of the new array?

Similar to this question, but not quite the same since this is a one-dimensional array and not python specific. I'm looking for a calculation. Thanks!

Community
  • 1
  • 1

2 Answers2

0

Let's say X - is the size of the row. In above example, X = 4.

For every X elements of the source array you need to:

  1. Duplicate each of them

    A1 A2 A3 A4

    becomes

    A1 A1 A2 A2 A3 A3 A4 A4

  2. Duplicate the whole "sub-array" you got in step 1

    A1 A1 A2 A2 A3 A3 A4 A4

    becomes

    A1 A1 A2 A2 A3 A3 A4 A4

    A1 A1 A2 A2 A3 A3 A4 A4

Ranty
  • 3,333
  • 3
  • 22
  • 24
0

Where is your problem? Just repeate each cell 1-4 times, then repeat the row 1-4 times...

def resize(data, width, height, factor):
  newdata = []
  for y in range(height):
     row = []
     for x in range(width):
       val = data[y*width + x]
       for r in range(factor):
         row.append( val )
     for r in range(factor):
       newdata.extend( row )
  return newdata

Obviously, you can have separate factors for x and y, and you don't actually need to know the height, just continue until you reach the end of the array. You can minimally optimize by computing y*width only once in the outer loop, and you can add some syntax sugar for appending the value "factor" times:

def resize(data, width, xfactor, yfactor):
  newdata = []
  offset = 0
  while offset + width < len(data):
     row = []
     for x in range(width):
       val = data[offset]
       row.extend( [val] * xfactor )
       offset += 1
     for r in range(yfactor):
       newdata.extend( row )
  return newdata

(the array multiplication syntax sugar probably will be slower than just appending with a for loop.)

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194