Skip to content

Instantly share code, notes, and snippets.

@damiancipolat
Created October 18, 2021 00:24
Show Gist options
  • Save damiancipolat/f3f488345312350f98a42a14e8054ce1 to your computer and use it in GitHub Desktop.
Save damiancipolat/f3f488345312350f98a42a14e8054ce1 to your computer and use it in GitHub Desktop.
Transponer matrices de 2 dimensione
/*
Transponer una matriz
Entrada:
1 2 3 4
5 6 7 8
Salida
1 5
2 6
3 7
4 8
*/
//Armo una funcion generador de matrices.
const createMatrix=(i:number,j:number):Array<Array<number>>=>{
const newList:Array<Array<number>>=[];
for (let i0=0;i0<=i-1;i0++){
const newRow:Array<number>=[];
for (let j0=0;j0<=j-1;j0++){
newRow.push(0);
}
newList.push(newRow);
}
return newList;
}
//Funcion transponedora de matrices de 2 dimensiones.
const transponerMatrix = (list:Array<Array<number>>):Array<Array<number>>=>{
//Detectar la matriz.
const rows = list.length;
//Valido solo matices de 2 dimensiones.
if (!(list.length>0))
throw new Error("La matriz debe tener dos dimensiones");
const cols = list[0].length;
//Creo una matriz nueva pero transpuesta vacia.
const transpuesta:Array<Array<number>> =createMatrix(cols,rows);
//Recorro las filas
list.forEach((row:Array<number>,i:number)=>{
//Recorro cada columna.
row.forEach((value:number,j:number)=>{
transpuesta[j][i]=value;
});
});
return transpuesta;
}
const list:Array<Array<number>>=[
[1,2,3,4,5],
[6,7,8,9,10]
];
console.log(transponerMatrix(list));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment