Last active
November 2, 2021 12:18
-
-
Save raffaele-abramini/51d0244d91fc8d132454255e78d52412 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function convert(s: string, numRows: number): string { | |
const chars = Array.from(s); | |
const rows: string[][] = []; | |
const I = 2; | |
chars.forEach((char, index) => { | |
const factor = (numRows * 2 - I) || 1; | |
const cycle = Math.floor(index / factor); | |
const phase = index - factor * cycle; | |
const isDiagonal = phase > (numRows - 1); | |
if (!isDiagonal) { | |
rows[phase] = rows[phase] || []; | |
rows[phase].push(char) | |
} else { | |
const diagonalPhase = phase - (numRows - 1); | |
rows[numRows - 1 - diagonalPhase].push(char); | |
} | |
}) | |
return rows.map(r => r.join("")).join(""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment