Skip to content
Advertisement

Mapping a string into a 2D Array for a “zig-zag” effect

first post, new to coding in js. I am trying to create a function that takes a (2) string array as an input such as [“coderbyte”, “3”], the first string being any random string. The second string represents the number of rows the function should create in a 2D array. The function should then print the first string in a zig zag pattern such as the following:

c   r   e
 o e b t 
  d   y  

The function should then return the word formed by combining the characters as it iterates through each row, eg “creoebtdy”. I have declared the empty array and using a while loop, managed to place the first three characters in the correct places in the array using the following code:

//initialize array of arrays of empty spaces
rows = Number(strArr[1])
columns = strArr[0].length
//console.log(rows)
//console.log(columns)
a = Array(rows).fill('').map(x => Array(columns).fill(''))

let i = 0

//a[0][0]= strArr[0][0]
while (i <= rows-1) {
  a[i][i]= strArr[0][i]
  //console.log(a)
  i++ 
}
//console.log(a)
//let j = i - 2
//console.log(i)
while (i >= rows && i < rows*2) {
  let j = i - 2
  a[j][i] = strArr[0][i]
  i++
  j--
}
console.log(a)

}
stringChal3(["coderbyte", "3"])

I am getting a “TypeError: Cannot set property ‘5’ of undefined” error at line 23 (a[j][i]…) when trying to place “e” and “r” in the array. I am unsure of how to fix the error. All help is much appreciated!

Advertisement

Answer

Since “All help is much appreciated“, here’s a completely different way of doing a zig-zag effect.

It comes from noticing that the zig zag pattern uses every 4th character in the top and bottom rows, but at different offsets/phases (0 for the top row and 2 for the bottom row), and the middle row uses every 2nd character (starting from the offset 1).

const zigzag = str => {
  const zig = (period, phase) => [...str]
    .map((character, index) => (index % period == phase) ? character : ' ')
    .join('');
  console.log(zig(4, 0));
  console.log(zig(2, 1));
  console.log(zig(4, 2));
}

zigzag('coderbyte');

Version supporting arbitrary number of rows

const zigzag = (str, rows) => {
  const zig = (period, phase) => [...str]
    .map((character, index) => [phase, period - phase].includes(index % period) ? character : ' ')
    .join('');
  for (let row = 0; row < rows; ++row) {
    console.log(zig(rows + rows - 2 || 1, row));
  }
}

zigzag('coderbyte', 3);

console.log('another example:');
zigzag('abcdefghijklmnopqrstuvwxyz', 5);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement