Skip to content Skip to sidebar Skip to footer

Print Words Vertically In Javascript

I'm trying to implement this algorithm in Javascript. Given a string s. Return all the words vertically in the same order in which they appear in s. Words are returned as a list of

Solution 1:

Basically, this is a series of simple operations:

  1. Split the string into words.
  2. Create a matrix (2d array). The longest word in the string is the height (row count) of the matrix and the length of the number of strings is the width (column count).
  3. Put the words in the string into the array rotated, that is, swap i and js where i is the row and j is the column.
  4. Join and trim the right side of each row.

constverticize = s => {
  const words = s.split(/\s+/);
  return [...Array(Math.max(...words.map(e => e.length)))]
    .map((_, i) => 
      [...Array(words.length)]
        .map((_, j) => words[j][i] || " ").join("").trimEnd());
};

console.log(verticize("CONTEST IS COMING"));

Solution 2:

You're never resetting the value of getBigWord so it's not working properly once you've seen a big word. Also it does not look like it would work properly for multiple big words.

This seems to work better:

var printVertically = function(s) {
  let ans = [];
  if(s === null || s.length === 0)
    return ans;

  let arr = s.split(" ");
  let biggest = 0;
  for(let i=0; i<arr.length; i++){
    if(arr[i].length > biggest)
      biggest = arr[i].length;
  }

  while(arr.length !== 0) {
    let word = arr.shift().split("");
    let getBigWord = falseif(word.length === biggest) {
      getBigWord = true;
    }
    for(i=0; i<biggest; i++){
      if(ans.length <= i)
        ans[i] = word[i] === undefined ? " " : word[i];
      elseif(word[i] !== undefined) {
        ans[i] += word[i];
      } elseif(!getBigWord) {
        ans[i] += " ";
      }
    }
  }

  for(i = 0; i < ans.length; i++) {
    // Modern version :// ans[i] = ans[i].trimRight(); 
    ans[i] = ans[i].replace(/\s+$/g, "");
  }

  return ans;
};

I need to trim at the end to avoid extra spaces

Post a Comment for "Print Words Vertically In Javascript"