Skip to content

Instantly share code, notes, and snippets.

@raffaele-abramini
Last active November 2, 2021 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raffaele-abramini/51d0244d91fc8d132454255e78d52412 to your computer and use it in GitHub Desktop.
Save raffaele-abramini/51d0244d91fc8d132454255e78d52412 to your computer and use it in GitHub Desktop.
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