Skip to content
Advertisement

How would I go about pasting an array over a 2D array?

The Objective

I need to take an array with data that can be displayed in 2 dimensions, and paste it over any part of a 2D array as if it were an image. This function would be similar to the Python library Pillow’s paste function.

Example

Say I have a 2D array with a size of 5×5, with a default value of 0.

JavaScript

And I have an average array with the length of 4, which can be assembled into 2×2 form.

JavaScript

With this, I need a function to, as if these arrays were images, ‘paste’ the second over the first. With a position (anchored from the top left) of (1,2), it would result in this 2D array.

JavaScript

My Attempt

Here is my attempt at creating the Python code.

JavaScript

The Problem

If you attempt to run the code above, you will see that it outputs this result.

JavaScript

This is the intended result.

JavaScript

I’ve tinkered with it a lot and haven’t found any answers online for why these arrays work the way they do here.

Any help is greatly appreciated.

Advertisement

Answer

When you initialise self.array [[0]*x]*y. The [0]*x is only shallow copied (reference only) y times, which means all of the row is basically the same array.

Since it is the same array, it’s final value would be the last row, i.e. 7,7,7,7,7,7,7,7. Thats why the one updated is such value.

Also noted the index is incorrect in the writeImage

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement