The task is to implement a decode function to reveal the hidden message in a given 2-D array of characters.
The boilerplate code
function decode(message) {
// your code here
}
If there's no hidden message, return an empty string
if (!message || message.length === 0 || message[0].length === 0) {
return '';
}
Define the grid's dimensions
const rows = message.length;
const cols = message[0].length;
Define variables to track the position and direction while moving through the grid
let row = 0;
let col = 0;
let goingDown = true;
let result = '';
When goingDown is true, it means the direction of movement is downwards to the right. If it is false, the direction of movement is upwards to the left. While moving across the grid, each character in a visited cell is collected and appended to the result.
while (col < cols && row >= 0 && row < rows) {
result += message[row][col];
}
Move down one row, and right one column as long as possible
if (row + 1 < rows && col + 1 < cols) {
row++;
col++;
}
When the bottom or the right edge is reached, move up one row and right one column
else {
goingDown = false;
if (col + 1 < cols) {
col++;
row--;
} else {
break;
}
}
}
When the top or right edge is reached, move down one row and right one column
else {
if (row - 1 >= 0 && col + 1 < cols) {
row--;
col++;
} else {
goingDown = true;
if (col + 1 < cols) {
col++;
row++;
} else {
break;
}
}
}
Stop when moving to the right is no longer possible
return result
The final code
function decode(message) {
// your code here
if (!message || message.length === 0 || message[0].length === 0) {
return '';
}
const rows = message.length;
const cols = message[0].length;
let row = 0;
let col = 0;
let goingDown = true;
let result = '';
while(col < cols && row >= 0 && row < rows) {
result += message[row][col];
if(goingDown) {
if(row + 1 < rows && col + 1 < cols) {
row++;
col++;
} else {
goingDown = false;
if(col + 1 < cols) {
col++;
row--;
} else {
break;
}
}
} else {
if(row - 1 >= 0 && col + 1 < cols) {
row--;
col++;
} else {
goingDown = true;
if(col + 1 < cols) {
col++;
row++;
} else {
break;
}
}
}
}
return result;
}
That's all folks!
Top comments (0)