Transpose of a Matrix

Medium Matrix
Transpose a matrix — turn its rows into columns.

Sample input

[[1, 2, 3], [4, 5, 6]]

Sample output

1 4 2 5 3 6

Solution

matrix = [[1, 2, 3], [4, 5, 6]]
rows = len(matrix)
cols = len(matrix[0])
for j in range(cols):
    print(" ".join(str(matrix[i][j]) for i in range(rows)))
const matrix = [[1, 2, 3], [4, 5, 6]];
const rows = matrix.length, cols = matrix[0].length;
for (let j = 0; j < cols; j++) {
  const row = [];
  for (let i = 0; i < rows; i++) row.push(matrix[i][j]);
  console.log(row.join(" "));
}
public class Main {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
        int rows = matrix.length, cols = matrix[0].length;
        for (int j = 0; j < cols; j++) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rows; i++) {
                sb.append(matrix[i][j]);
                if (i < rows - 1) sb.append(" ");
            }
            System.out.println(sb.toString());
        }
    }
}
fun main() {
    val matrix = arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6))
    val rows = matrix.size
    val cols = matrix[0].size
    for (j in 0 until cols) {
        val row = StringBuilder()
        for (i in 0 until rows) {
            row.append(matrix[i][j])
            if (i < rows - 1) row.append(" ")
        }
        println(row.toString())
    }
}
let matrix = [[1, 2, 3], [4, 5, 6]]
let rows = matrix.count
let cols = matrix[0].count
for j in 0..<cols {
    var row = [String]()
    for i in 0..<rows {
        row.append(String(matrix[i][j]))
    }
    print(row.joined(separator: " "))
}
void main() {
  List<List<int>> matrix = [[1, 2, 3], [4, 5, 6]];
  int rows = matrix.length;
  int cols = matrix[0].length;
  for (int j = 0; j < cols; j++) {
    List<int> row = [];
    for (int i = 0; i < rows; i++) {
      row.add(matrix[i][j]);
    }
    print(row.join(' '));
  }
}
#include <iostream>
using namespace std;

int main() {
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int rows = 2, cols = 3;
    for (int j = 0; j < cols; j++) {
        for (int i = 0; i < rows; i++) {
            cout << matrix[i][j];
            if (i < rows - 1) cout << " ";
        }
        cout << endl;
    }
    return 0;
}
#include <stdio.h>

int main() {
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int rows = 2, cols = 3;
    for (int j = 0; j < cols; j++) {
        for (int i = 0; i < rows; i++) {
            printf("%d", matrix[i][j]);
            if (i < rows - 1) printf(" ");
        }
        printf("\n");
    }
    return 0;
}