Convert 1D Array Into 2D Array
To create the 2D array, you need to first check if the length of the original array is equal to m*n. If it’s not, return an empty array because you can’t form a 2D array with m rows and n columns. If it is, you can start forming your 2D array.
Here’s a python solution:
|
|
This solution works by iterating through the original array with steps of size n
, and in each step, it creates a sublist of size n
and adds it to the result. The range
function starts from 0
and goes till len(original)
with steps of size n
.
For each i
, it extracts the sublist original[i:i+n]
and adds it to the result. This is done until all elements of original
are processed.
If the size of original
is not equal to m*n
, it means we can’t form a 2D array of size m
by n
using the elements of original
, so we return an empty list in that case.
For m=2,n=2
i i/n i%n [ ][ ]
0] 0/2 0%2 [0][0]
1] 1/2 1%2 [0][1]
2] 2/2 2%2 [1][0]
3] 3/2 3%2 [1][1]
|
|