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:

JavaScript

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).

JavaScript

Version supporting arbitrary number of rows

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement