I am trying to solve the GeeksForGeeks problem Concatenation of Zig-Zag String in n Rows:
Given a string and number of rows ānā. Print the string formed by concatenating n rows when the input string is written in row-wise Zig-Zag fashion.
Example 1:
Input:
str = "ABCDEFGH" n = 2
Output:
"ACEGBDFH"
Explanation:
Let us write input string in Zig-Zag fashion in 2 rows.
A C E G B D F H
Now concatenate the two rows and ignore spaces in every row. We get
"ACEGBDFH"
My code outputs the correct answer, except that it is not output all on one line, and it prints undefined
after every test case I have tried.
I can't figure out what I did to get this answer or how to get the results to print one line.
function StringChallenge(strArr) {
let str = strArr[0];
let n = strArr[1];
if (n == 1) {
console.log(str);
return;
}
let str1 = str.split("");
let len = str.length;
let arr = new Array(n);
for (let i = 0; i < n; i++) {
arr[i] = "";
}
let row = 0;
let down = true;
for (let i = 0; i < len; i++) {
arr[row] += (str1[i]);
if (row == n - 1) {
down = false;
} else if (row == 0){
down = true;
}
if (down) {
row++
} else {
row--;
}
}
for (let i = 0; i < n; ++i) {
console.log(arr[i]);
}
}
let strArr = ["geeksforgeeks", 3]; // test 1. should print gsgsekfrekeoe
//let strArr = ["cat", 5];// test 2. should print cat
console.log(StringChallenge(strArr));