* ZigZag.js
/*
https://leetcode.com/problems/zigzag-conversion/
"PAYPALISHIRING"
row x 3
P A H N
A P L S I I G
Y I R
*/
function ZigZag() {}
String.prototype.forEach = function(fn) {
for (var i = 0; i < this.length; i++) {
fn( this.charAt(i) );
}
};
ZigZag.convert = function(/* String */ s, /* Number */ numRows) {
if (numRows === 1) {
return s;
}
var rows = [], n = Math.min(numRows, s.length);
for (var i = 0; i < n; i++) {
rows[i] = "";
}
var curRow = 0, goingDown = false;
s.forEach(function(c) {
// rows[curRow] += c;
rows[curRow] = rows[curRow] ? rows[curRow] + c : "" + c;
if (curRow === 0 || curRow === numRows - 1) {
goingDown = ! goingDown;
}
curRow += goingDown ? 1 : -1;
});
console.debug(rows);
return rows.join("");
};
ZigZag.convert2 = function(/*String */s, /*Nubmer */ numRows) {
if (numRows === 1) {
return s;
}
var ret = "";
var n = s.length;
var cycleLen = 2 * numRows - 2;
for (var i = 0; i < numRows; i++) {
for (var j = 0; j + i < n; j += cycleLen) {
ret += s.charAt(j+i);
if (i !== 0 && i !== numRows - 1 && j + cycleLen - i < n) {
ret += s.charAt( j + cycleLen - i );
}
}
}
return ret;
};
ZigZag.convert3 = function(s, numRows) {
if (numRows === 1) { return s;}
var n = s.length;
var b = "";
for (var i = 0; i < numRows; i++) {
for (var j = i; j < n; ) {
b += s.charAt(j);
// We set j to the next value in the same row and the next column
j += numRows + numRows - 2;
// If current row is 0 or numRows - 1 there is no element in the diagonal between columns to consider
if (i === 0 || i === numRows-1) {
continue;
}
// Set j to the value in the same row and in the diagonal between and next column
j -= i + i
// Validate that j is a valid index
if (j >= n) {
break;
}
b += s.charAt(j);
// Set j back again to the value in the same row and the next column
j += i + i;
}
}
return b;
};
test:
var s = "PAYPALISHIRING";
console.log( ZigZag.convert(s, 3) ); // "PAHNAPLSIIGYIR"
console.log( ZigZag.convert2(s, 4) ); // "PINALSIGYAHRPI"
console.log( ZigZag.convert3(s, 3) ); // "PAHNAPLSIIGYIR"
node ZigZag.js
[ 'PAHN', 'APLSIIG', 'YIR' ]
PAHNAPLSIIGYIR
PINALSIGYAHRPI
PAHNAPLSIIGYIR