| 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.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 | // Create a result grid as a 2D array, copying the input |
| 21 | const result = input.map(row => row.split('')); |
| 22 | |
| 23 | // Define the 8 possible directions (horizontal, vertical, diagonal) |
| 24 | const directions = [ |
| 25 | [-1, -1], [-1, 0], [-1, 1], |
| 26 | [0, -1], [0, 1], |
| 27 | [1, -1], [1, 0], [1, 1] |
| 28 | ]; |
| 29 | |
| 30 | // Iterate through each cell in the grid |
| 31 | for (let i = 0; i < rows; i++) { |
| 32 | for (let j = 0; j < cols; j++) { |
| 33 | // If the cell is a flower, keep it as is |
| 34 | if (input[i][j] === '*') { |
| 35 | result[i][j] = '*'; |
| 36 | } else { |
| 37 | // Count adjacent flowers |
| 38 | let count = 0; |
| 39 | |
| 40 | // Check all 8 directions |
| 41 | for (const [dx, dy] of directions) { |
| 42 | const ni = i + dx; |
| 43 | const nj = j + dy; |
| 44 | |
| 45 | // Edge Case: Check if the neighbor is within bounds |
| 46 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 47 | if (input[ni][nj] === '*') { |
| 48 | count++; |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // Edge Case: If count is zero, leave the cell empty (as it was) |
| 54 | // Otherwise, replace with the count |
| 55 | if (count > 0) { |
| 56 | result[i][j] = count.toString(); |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // Convert the result grid back to an array of strings |
| 63 | return result.map(row => row.join('')); |
| 12 | 64 | }; |
| 65 | |
| 66 | // Handled Edge Cases: Empty input array, input with empty strings, neighbor bounds checking, zero count cells |