commit 65186a36a156f06f8ea2fb3b2556db362140711e Author: Aerex Date: Mon Nov 25 09:17:57 2019 -0600 feat: Added zig-zag-converstion for js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d63cd90 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.gtm/ diff --git a/zig-zag-conversion/js/index.js b/zig-zag-conversion/js/index.js new file mode 100644 index 0000000..3ca0d61 --- /dev/null +++ b/zig-zag-conversion/js/index.js @@ -0,0 +1,114 @@ +/* +The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) + +P A H N +A P L S I I G +Y I R +And then read line by line: "PAHNAPLSIIGYIR" + +Write the code that will take a string and make this conversion given a number of rows: + +string convert(string s, int numRows); +Example 1: + +Input: s = "PAYPALISHIRING", numRows = 3 +Output: "PAHNAPLSIIGYIR" +Example 2: + +Input: s = "PAYPALISHIRING", numRows = 4 +Output: "PINALSIGYAHRPI" +Explanation: + +P I N +A L S I G +Y A H R +P I +*/ + +/** + * @param {string} s + * @param {number} numRows + * @return {string} + */ +const convert = (s, numRows) => { + const pattern = []; + let x = 0; + let y = 0; + let goingDown = true; + for(let i = 0; i < s.length; i++){ + if (y === numRows && goingDown) { + y = numRows - 2; + x++; + goingDown = false; + } + if (y == -1 && !goingDown){ + y = 1; + x++; + goingDown = true; + } + + if (!pattern[x]){ + pattern[x] = []; + } + pattern[x][y] = s[i]; + if (goingDown){ + y++; + } else { + y--; + } + } + + let col = 0; + let output=''; + let j = 0; + // Time complexity: O(n) + while (j < s.length) { + // Reset col counter to 0 if at the last col + if (col === pattern.length) { + col = 0; + } + // Remove empty cols from list then skip + if (!pattern[col] || pattern[col].length === 0){ + pattern.splice(col, 1); + continue; + } + + const char = pattern[col][0]; + // Add character to output and increment char counter + // Don't increment if character is null + // char can be null since we were not adding elements in every index + if (char) { + output+=char; + j++; + } + pattern[col].shift(); + col++; + } + return output; +}; + +let s, numRows; +/* Test Case 1 + * Input s = "PAYPALISHIRING", numRows = 3 + * Output: "PAHNAPLSIIGYIR" + */ + +s = 'PAYPALISHIRING'; +numRows = 3; +console.log(convert(s, numRows)); + +/* Test Case 2 + * Input: s = "PAYPALISHIRING", numRows = 4 + * Output: "PINALSIGYAHRPI" + */ +s = 'PAYPALISHIRING'; +numRows = 4; +console.log(convert(s, numRows)); + +/* Test Case 3 + * Input: s = "AB", numRows = 1 + * Output: "AB" + */ +s = 'AB'; +numRows = 1; +console.log(convert(s, numRows));