| 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 | const result = []; |
| 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 | // Directions for 8 adjacent cells (horizontal, vertical, diagonal) |
| 28 | const directions = [ |
| 29 | [-1, -1], [-1, 0], [-1, 1], |
| 30 | [0, -1], [0, 1], |
| 31 | [1, -1], [1, 0], [1, 1] |
| 32 | ]; |
| 33 | |
| 34 | for (let i = 0; i < rows; i++) { |
| 35 | let newRow = ''; |
| 36 | for (let j = 0; j < cols; j++) { |
| 37 | // If current cell is a flower, keep it as is |
| 38 | if (input[i][j] === '*') { |
| 39 | newRow += '*'; |
| 40 | } else { |
| 41 | // Count adjacent flowers |
| 42 | let count = 0; |
| 43 | for (const [dx, dy] of directions) { |
| 44 | const ni = i + dx; |
| 45 | const nj = j + dy; |
| 46 | |
| 47 | // Edge Case: Check bounds to avoid accessing invalid indices |
| 48 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 49 | if (input[ni][nj] === '*') { |
| 50 | count++; |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // Edge Case: If no adjacent flowers, leave cell empty |
| 56 | if (count === 0) { |
| 57 | newRow += ' '; |
| 58 | } else { |
| 59 | newRow += count.toString(); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | result.push(newRow); |
| 64 | } |
| 65 | |
| 66 | return result; |
| 12 | 67 | }; |
| 68 | |
| 69 | // Handled Edge Cases: Empty input array, rows with different lengths, accessing invalid indices, no adjacent flowers |