skip to Main Content

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!

  1. When cols = 3, rows = 3
    Input:
0 | 1 | 2
3 | 4 | 5
6

Expected:

0 | 3 | 5
1 | 4 | 6
2 | 
  1. 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


  1. The best I can do (…actually)

    function convert ( arr2D )
      {
      let 
        xIn = arr2D.flat()
      , xRP = arr2D.reduce((a,x,i)=>(a.R[i]=[], x.forEach((_,j)=>a.P.push({i,j})),a),{R:[],P:[]})
        ;
      xRP.P
        .sort((a,b)=>(a.j-b.j)||(a.i-b.i))
        .forEach( ({i,j})=>xRP.R[i][j]=xIn.shift())
        ;
      return xRP.R
      }
    const
      arrIn  = [[0, 1, 2], [3, 4, 5], [6]]
    , arrOut = convert( arrIn )
      ;
    console.log( JSON.stringify( arrOut )); // [[0,3,5],[1,4,6],[2]]   
    Login or Signup to reply.
  2. Here is a small method in Java, which performs the operation.

    void change( int arr[][] ) {
       String numeros[] = Arrays.deepToString( arr ).replace( "[", "" ).replace( "]", "" ).split( ", " );
       int k = numeros.length - 1;
       for( int j = arr[ 0 ].length - 1; j >= 0; j -- ) {
          for( int i = arr.length - 1; i >= 0; i -- ) {
             if( arr[ i ].length - 1 >= j ) {
                arr[ i ][ j ] = Integer.parseInt( numeros[ k -- ] );
             }
          }
       }
       System.out.println( Arrays.deepToString( arr ) );
    }
    

    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.

    Login or Signup to reply.
  3. 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 the i-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

    public static <T extends Comparable<T>> void vertSort(T[][] mat) {
        //Retrieving the size of the largest su-array
        int maxCol = Arrays.stream(mat).mapToInt(v -> v.length).max().orElse(0);
        T temp;
    
        //Iterating columns and for each column its rows
        for (int j = 0; j < maxCol; j++) {
            for (int i = 0; i < mat.length; i++) {
    
                //Skipping the j-th column if this is not present for the current sub-array
                if (j >= mat[i].length) {
                    continue;
                }
    
                //Iterating columns and for each column its rows
                for (int j2 = j; j2 < maxCol; j2++) {
    
                    //Selection sort approach where i2 is initialized to the next element if we're still on the same column
                    //or to 0 if we've moved forward
                    for (int i2 = j2 == j ? i + 1 : 0; i2 < mat.length; i2++) {
    
                        //Skipping the j2-th column if this is not present for the current sub-array
                        if (j2 >= mat[i2].length) {
                            continue;
                        }
    
                        //If a following element is lower than the current one than they're swapped
                        if (mat[i2][j2].compareTo(mat[i][j]) < 0) {
                            temp = mat[i][j];
                            mat[i][j] = mat[i2][j2];
                            mat[i2][j2] = temp;
                        }
                    }
                }
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search