| 4 | 4 | // |
| 5 | 5 | |
| 6 | 6 | /** |
| 7 | | * @param {string[]} input |
| 8 | | * @returns {string[]} |
| 7 | * Annotates a flower field by replacing empty spaces with the count of adjacent flowers. |
| 8 | * @param {string[]} input - A 2D array represented as a list of strings, where each string is a row. |
| 9 | * '*' represents a flower, ' ' represents an empty space. |
| 10 | * @returns {string[]} - The annotated flower field with counts replacing empty spaces. |
| 9 | 11 | */ |
| 10 | 12 | export const annotate = (input) => { |
| 11 | | throw new Error('Remove this statement and implement this function'); |
| 13 | // Edge Case: Handle empty input |
| 14 | if (!input || input.length === 0) { |
| 15 | return []; |
| 16 | } |
| 17 | |
| 18 | const rows = input.length; |
| 19 | const cols = input[0].length; |
| 20 | const result = []; |
| 21 | |
| 22 | // Edge Case: Handle rows with inconsistent lengths |
| 23 | for (let i = 0; i < rows; i++) { |
| 24 | if (input[i].length !== cols) { |
| 25 | throw new Error('All rows must have the same length'); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | // Directions for 8 neighbors (horizontal, vertical, diagonal) |
| 30 | const directions = [ |
| 31 | [-1, -1], [-1, 0], [-1, 1], |
| 32 | [0, -1], [0, 1], |
| 33 | [1, -1], [1, 0], [1, 1] |
| 34 | ]; |
| 35 | |
| 36 | for (let i = 0; i < rows; i++) { |
| 37 | let newRow = ''; |
| 38 | for (let j = 0; j < cols; j++) { |
| 39 | // If the current cell is a flower, keep it as is |
| 40 | if (input[i][j] === '*') { |
| 41 | newRow += '*'; |
| 42 | } else { |
| 43 | // Count adjacent flowers |
| 44 | let count = 0; |
| 45 | for (const [dx, dy] of directions) { |
| 46 | const ni = i + dx; |
| 47 | const nj = j + dy; |
| 48 | |
| 49 | // Edge Case: Check bounds to avoid accessing invalid indices |
| 50 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 51 | if (input[ni][nj] === '*') { |
| 52 | count++; |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | // Edge Case: If no adjacent flowers, leave the cell empty |
| 58 | if (count === 0) { |
| 59 | newRow += ' '; |
| 60 | } else { |
| 61 | newRow += count.toString(); |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | result.push(newRow); |
| 66 | } |
| 67 | |
| 68 | // Handled Edge Cases: Empty input, inconsistent row lengths, out-of-bounds access, no adjacent flowers |
| 69 | return result; |
| 12 | 70 | }; |