| 8 | 8 | * @returns {string[]} |
| 9 | 9 | */ |
| 10 | 10 | export const annotate = (input) => { |
| 11 | | throw new Error('Remove this statement and implement this function'); |
| 11 | // Edge Case: Handle empty input |
| 12 | if (!input || input.length === 0) { |
| 13 | return []; |
| 14 | } |
| 15 | |
| 16 | // Edge Case: Handle input with empty strings |
| 17 | const rows = input.length; |
| 18 | const cols = input[0] ? input[0].length : 0; |
| 19 | |
| 20 | // Edge Case: Handle grid with no columns |
| 21 | if (cols === 0) { |
| 22 | return input; |
| 23 | } |
| 24 | |
| 25 | // Create a result grid as a 2D array |
| 26 | const result = Array(rows).fill().map(() => Array(cols).fill('')); |
| 27 | |
| 28 | // Helper function to count adjacent flowers |
| 29 | const countAdjacentFlowers = (row, col) => { |
| 30 | let count = 0; |
| 31 | // Check all 8 adjacent positions |
| 32 | for (let i = -1; i <= 1; i++) { |
| 33 | for (let j = -1; j <= 1; j++) { |
| 34 | // Skip the cell itself |
| 35 | if (i === 0 && j === 0) continue; |
| 36 | |
| 37 | const newRow = row + i; |
| 38 | const newCol = col + j; |
| 39 | |
| 40 | // Check if the adjacent position is within bounds |
| 41 | if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) { |
| 42 | // Check if there's a flower in the adjacent position |
| 43 | if (input[newRow][newCol] === '*') { |
| 44 | count++; |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | return count; |
| 50 | }; |
| 51 | |
| 52 | // Process each cell in the grid |
| 53 | for (let i = 0; i < rows; i++) { |
| 54 | for (let j = 0; j < cols; j++) { |
| 55 | // Edge Case: Handle undefined or null characters |
| 56 | const cell = input[i] && input[i][j] ? input[i][j] : ' '; |
| 57 | |
| 58 | if (cell === '*') { |
| 59 | // If it's a flower, keep it as is |
| 60 | result[i][j] = '*'; |
| 61 | } else { |
| 62 | // If it's an empty space, count adjacent flowers |
| 63 | const flowerCount = countAdjacentFlowers(i, j); |
| 64 | if (flowerCount === 0) { |
| 65 | // Edge Case: No adjacent flowers, leave empty |
| 66 | result[i][j] = ' '; |
| 67 | } else { |
| 68 | // Replace with the count of adjacent flowers |
| 69 | result[i][j] = flowerCount.toString(); |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | // Convert the 2D array back to an array of strings |
| 76 | return result.map(row => row.join('')); |
| 77 | |
| 78 | // Handled Edge Cases: empty input, input with empty strings, grid with no columns, undefined/null characters, no adjacent flowers |
| 12 | 79 | }; |