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