I want to convert the 2d array which is missing some values and has been sorted from left to right to a new array which is sorted from top to bottom like below examples. Cols and rows and the number of items in the array are dynamic, can be changed to any number. Thank you!
- When cols = 3, rows = 3
Input:
0 | 1 | 2
3 | 4 | 5
6
Expected:
0 | 3 | 5
1 | 4 | 6
2 |
- When cols = 5, rows = 2
Input:
0 | 1 | 2 | 3 | 4
5 | 6
Expected:
0 | 2 | 4 | 5 | 6
1 | 3
UPDATE with code JavaScript code
const input = [[0, 1, 2], [3, 4, 5], [6]];
const expected = convert(input);
// expected = [[0, 3, 5], [1, 4, 6], [2]];
const input = [[0, 1, 2, 3, 4], [5, 6]];
const expected = convert(input);
// expected = [[0, 2, 4, 5, 6], [1, 3]];
UPDATE 2
I have tried this way:
const input = [[0,1,2],
[3,4,5],
[6]];
const array = flatToArray(input);
console.log("--- Array:---");
console.log(array);
const rows = input.length;
const cols = input[0].length;
const result = [];
for (let i = 0; i < rows; i++) {
result[i] = [];
for (let j = 0; j < cols; j++) {
result[i].push(array[i%rows + j*rows]);
}
}
function flatToArray(input) {
return input.reduce((prev, current) => prev.concat(current), []);
}
console.log("--- Final:---");
console.log(result)
Output:
--- Array:---
[
0, 1, 2, 3,
4, 5, 6
]
--- Final:---
[ [ 0, 3, 6 ], [ 1, 4, undefined ], [ 2, 5, undefined ] ]
3
Answers
The best I can do (…actually)
Here is a small method in Java, which performs the operation.
As you can see, first I convert the "2D" array to a single dimension (of String), then all that remains is to iterate in "reverse", verify that the current row has the minimum length, and assign the corresponding value.
General Logic
Here is an attempt using the selection sort logic for a generic
Comparable
type.At the beginning, it’s retrieved the largest sub-array’s size to iterate through the columns first, and then for each column iterate through its rows. At each iteration, it’s first made sure that the current
j-th
column is present for thei-th
sub-array. Then, the method looks for a smaller element among the following ones, and when it’s found, the smaller value is swapped with the current one.Demo
Here is a demo at OneCompiler with your 2 test cases.
Java Implementation