Zigzag conversion

    0

    1

    pavan koka

    This function converts a string s into an array obj of integers. The string s is divided into numRows sections, where each section is either a single character or a substring of the string that starts at the section number 2*numRows - 2 and ends at the section number before the current section.

    The pattern is a 2*numRows - 2 array of numbers. The first numRows elements of the pattern are the section numbers. The second numRows elements of the pattern are the section numbers except for the first element, which is 1. The function checks if the section number passed in is in the pattern. If it isn't, the function returns the string s. Otherwise, the function iterates through the string s and grabs each character or substring that is a part of the section number in the pattern. The function also assigns that character or substring to the variable obj[row], if it exists. The function then returns the value of obj[row].join(''), which is the string that is stored in the variable result.

    var convert = function(s, numRows) {
      const pattern = 2*numRows - 2;
      const obj = {};
    
      if(!pattern || s.length < 2) {
        return s;
      }
    
      for(let i=0; i<s.length; i++) {
        const patternNum = i % pattern;
        if(patternNum < numRows) {
          const row = patternNum;
          if(obj[row]) {
            obj[row].push(s[i])
          } else {
            obj[row] = [s[i]]
          }
        } else {
          const row = numRows - (patternNum - numRows) - 2;
          if(obj[row]) {
            obj[row].push(s[i])
          } else {
            obj[row] = [s[i]]
          }
        }
      }
      let result = '';
      for(let i=0; i<numRows; i++) {
        result += obj[i] && obj[i].length ? obj[i].join('') : ''
      }
      return result
    };
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.