Given a 2-dimensional jagged array and a fill value, pad the array in both dimensions with the fill value to ensure that it is square and not jagged (i.e., all rows are the same length, and that length is the same as the number of rows).
The fill values should always be added to the "edges", which may be the start or the end, but not in the middle.
For example, with the fill value 8
, this array:
[[1, 5, 3],
[4, 5],
[1, 2, 2, 5]]
could become:
[[1, 5, 3, 8],
[4, 5, 8, 8],
[1, 2, 2, 5],
[8, 8, 8, 8]]
Here is another valid output:
[[8, 8, 8, 8],
[8, 1, 5, 3],
[8, 4, 5, 8],
[1, 2, 2, 5]]
However, the padding should be minimal: the size of the output square should be equal to the maximum of the length of the rows and the number of rows. For example, this is not a valid output for the input above:
[[1, 5, 3, 8, 8],
[4, 5, 8, 8, 8],
[1, 2, 2, 5, 8],
[8, 8, 8, 8, 8],
[8, 8, 8, 8, 8]]
More test cases
All using fill value 0
for simplicity.
Input:
[]
Output:
[]
Input:
[[],
[]]
Output:
[[0, 0],
[0, 0]]
Input:
[[5]]
Output:
[[5]]
Input:
[[0, 0],
[0],
[0, 0, 0]]
Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
Input:
[[1, 2, 3, 4]]
Output:
[[1, 2, 3, 4],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
Input:
[[1],
[2],
[3],
[4, 5]]
Output:
[[1, 0, 0, 0],
[2, 0, 0, 0],
[3, 0, 0, 0],
[4, 5, 0, 0]]
Rules
- The array's elements and the fill value can be of whatever type or set of values you like, as long as there are at least two distinct possibilities. For example, you could use characters, where the array is a multi-line string (where each line is a row), or you could restrict the values to single digits...
- Standard loopholes are forbidden
- Standard I/O rules apply
- This is code-golf, so the shortest code in bytes wins
[[1],[2],[3],[4,5]]
(from examples), can we also output[[0,0,1,0],[0,0,2,0],[0,0,3,0],[0,0,4,5]]
? \$\endgroup\$