Skip to content

Instantly share code, notes, and snippets.

@germanescobar
Created February 4, 2023 00:23
Show Gist options
  • Save germanescobar/8b5b3ed1fd2d80574582c7f4367c1b5d to your computer and use it in GitHub Desktop.
Save germanescobar/8b5b3ed1fd2d80574582c7f4367c1b5d to your computer and use it in GitHub Desktop.
var convert = function(s, numRows) {
if (numRows === 1) return s
const mat = buildMatrix(s, numRows)
return buildResult(mat)
};
function buildMatrix(s, numRows) {
const mat = initMatrix(numRows)
let r = 0, c = 0, down = true
for (let i=0; i < s.length; i++) {
mat[r][c] = s[i]
if (down && r === mat.length - 1) {
down = false
} else if (!down && r === 0) {
down = true
}
if (down) {
r++
} else {
r--
c++
}
}
return mat
}
function initMatrix(numRows) {
const mat = []
for (let i=0; i < numRows; i++) {
mat[i] = []
}
return mat
}
function buildResult(mat) {
let result = ""
for (let i=0; i < mat.length; i++) {
for (let j=0; j < mat[i].length; j++) {
if (mat[i][j]) result += mat[i][j]
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment