Skip to content

Latest commit

 

History

History
67 lines (49 loc) · 1.14 KB

File metadata and controls

67 lines (49 loc) · 1.14 KB

9. decode message

Problem

https://bigfrontend.dev/problem/decode-message

Problem Description

Your are given a 2-D array of characters. There is a hidden message in it.

I B C A L K A
D R F C A E A
G H O E L A D

The way to collect the message is as follows

  1. start at top left
  2. move diagonally down right
  3. when cannot move any more, try to switch to diagonally up right
  4. when cannot move any more, try switch to diagonally down right, repeat 3
  5. stop when cannot neither move down right or up right. the character on the path is the message for the input above, IROCLED should be returned.

notes

if no characters could be collected, return empty string

Solution

/**
 * @param {string[][]} message
 * @return {string}
 */
function decode(message) {
  const result = [];
  let x = 0;
  let y = 0;
  let dir = 'down';

  while (message[x] && message[x][y]) {
    result.push(message[x][y]);

    if (dir === 'down') {
      x++;
    } else {
      x--;
    }

    if (x === 0) {
      dir = 'down';
    } else if (x === message.length - 1) {
      dir = 'up';
    }

    y++;
  }

  return result.join('');
}