“Matrix Transpose JavaScript” Respostas de código

Matrix Transpose JavaScript

//One-liners inspired by Fawad Ghafoor and Óscar Gómez Alcañiz

function transpose(matrix) {
  return matrix[0].map((col, i) => matrix.map(row => row[i]));
}

function transpose(matrix) {
  return matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c]));
}
//Functional approach style with reduce by Andrew Tatomyr

function transpose(matrix) {
  return matrix.reduce((prev, next) => next.map((item, i) =>
    (prev[i] || []).concat(next[i])
  ), []);
}
//Lodash/Underscore by marcel

function tranpose(matrix) {
  return _.zip(...matrix);
}

// Without spread operator.
function transpose(matrix) {
  return _.zip.apply(_, [[1,2,3], [1,2,3], [1,2,3]])
}
Even simpler Lodash/Underscore solution by Vigrant

_.unzip(matrix);
Vanilla approach

function transpose(matrix) {
  const rows = matrix.length, cols = matrix[0].length;
  const grid = [];
  for (let j = 0; j < cols; j++) {
    grid[j] = Array(rows);
  }
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      grid[j][i] = matrix[i][j];
    }
  }
  return grid;
}
//Vanilla in-place ES6 approach inspired by Emanuel Saringan

function transpose(matrix) {
  for (var i = 0; i < matrix.length; i++) {
    for (var j = 0; j < i; j++) {
      const temp = matrix[i][j];
      matrix[i][j] = matrix[j][i];
      matrix[j][i] = temp;
    }
  }
}

// Using destructing
function transpose(matrix) {
  for (var i = 0; i < matrix.length; i++) {
    for (var j = 0; j < i; j++) {
      [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
    }
  }
}
code fighter

transpor da matriz em JavaScript

class Solution {
    solve(matrix) {
        let arr=[];
        for(let i=0;i<matrix.length;i++){
            arr.push([])
            for(let j=0;j<matrix.length;j++){
                arr[i].push(matrix[j][i])
            }
        }
        return arr
    }
}
Courageous Caiman

Respostas semelhantes a “Matrix Transpose JavaScript”

Perguntas semelhantes a “Matrix Transpose JavaScript”

Procure respostas de código populares por idioma

Procurar outros idiomas de código