1

On the function below, I'm trying to reshape a string into W-like shape, and made a new output with new arrangement based on its totalLevel, check the test case at the end of the script for more clarity. I'm using nodejs, and came up with idea using objects. But I have no clue on how to take the next str[i] after it reach the totalLevel. Thanks for any helps!

function shapeOfW (str, totalLevel) {
var obj = {}
var position = 0

    for (var i = 0; i < str.length; i++) {
            obj[position+1] = (str[i])
            position++
                if (posisi == totalLevel) {
                    break
                }

    }

return obj
}

//TEST CASE
console.log (shapeOfW('ABCDEFG', 3))//AEBDFCG

/*
    Input           : ABCDE
    Transformed into:   1| A       E
                        2|   B   D   F
                        3|     C       G

    OUTPUT          : AEBDFCG               
*/
Sofyan Thayf
  • 1,322
  • 2
  • 14
  • 26

1 Answers1

0

You could use a bidimensional array (an array of arrays) instead of an object to better represent a bidimensional space positioning of your letters (with x and y coordinates).

Here is an example (with a bonus formatted console.log);

function shapeOfW(str, totalLevel) {
  var array = [];
  var stepY = 1;

  for (var x = 0, y = 0; x < str.length; x += 1, y += stepY) {
    array[y] = array[y] || str.split('').map(() => ".");
    array[y][x] = str[x];
    if (x && x % (totalLevel - 1) === 0) {
      stepY = -stepY;
    }
  }

  return array;
}

function consoleLog(array) {
  const log = array.map(arr => arr.join(' ')).join('\n');
  console.log(log);
}

function join(array) {
  const log = array.map(arr => arr.filter(i => i !== '.').join('')).join('');
  console.log(log);
}

//TEST CASE
consoleLog(shapeOfW('ABCDEFG', 3))
join(shapeOfW('ABCDEFG', 3))

/*
Input           : ABCDE
Transformed into:   1| A       E
                    2|   B   D   F
                    3|     C       G

OUTPUT          : AEBDFCG               
*/
giuseppedeponte
  • 2,366
  • 1
  • 9
  • 19