| 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 array |
| 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].length; |
| 19 | |
| 20 | // Edge Case: Handle rows with different lengths |
| 21 | for (let i = 0; i < rows; i++) { |
| 22 | if (input[i].length !== cols) { |
| 23 | throw new Error('All rows must have the same length'); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | // Create a result grid as a 2D array |
| 28 | const result = Array(rows); |
| 29 | for (let i = 0; i < rows; i++) { |
| 30 | result[i] = input[i].split(''); |
| 31 | } |
| 32 | |
| 33 | // Define the 8 possible directions (horizontal, vertical, diagonal) |
| 34 | const directions = [ |
| 35 | [-1, -1], [-1, 0], [-1, 1], |
| 36 | [0, -1], [0, 1], |
| 37 | [1, -1], [1, 0], [1, 1] |
| 38 | ]; |
| 39 | |
| 40 | // For each cell in the grid |
| 41 | for (let row = 0; row < rows; row++) { |
| 42 | for (let col = 0; col < cols; col++) { |
| 43 | // If the cell is empty, count adjacent flowers |
| 44 | if (input[row][col] === ' ') { |
| 45 | let count = 0; |
| 46 | |
| 47 | // Check all 8 directions |
| 48 | for (const [dx, dy] of directions) { |
| 49 | const newRow = row + dx; |
| 50 | const newCol = col + dy; |
| 51 | |
| 52 | // Edge Case: Check if the adjacent cell is within bounds |
| 53 | if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) { |
| 54 | if (input[newRow][newCol] === '*') { |
| 55 | count++; |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // Edge Case: Only replace empty cell with count if count > 0 |
| 61 | if (count > 0) { |
| 62 | result[row][col] = count.toString(); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | // Convert each row back to a string |
| 69 | return result.map(row => row.join('')); |
| 12 | 70 | }; |
| 71 | |
| 72 | // Handled Edge Cases: Empty input array, input with empty strings, rows with different lengths, adjacent cell boundary checks, replacing empty cells only when count > 0 |