| 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 - An array of strings representing the flower field grid |
| 9 | * @returns {string[]} - An array of strings with annotations added |
| 9 | 10 | */ |
| 10 | 11 | export const annotate = (input) => { |
| 11 | | throw new Error('Remove this statement and implement this function'); |
| 12 | | }; |
| 12 | // Edge Case: Handle empty input |
| 13 | if (!input || input.length === 0) { |
| 14 | return []; |
| 15 | } |
| 16 | |
| 17 | const rows = input.length; |
| 18 | const cols = input[0].length; |
| 19 | |
| 20 | // Edge Case: Handle input with empty strings |
| 21 | if (cols === 0) { |
| 22 | return input; |
| 23 | } |
| 24 | |
| 25 | // Convert input strings to arrays for easier manipulation |
| 26 | const grid = input.map(row => row.split('')); |
| 27 | |
| 28 | // Create a new grid for the result to avoid modifying the original during processing |
| 29 | const result = grid.map(row => [...row]); |
| 30 | |
| 31 | // Define the 8 possible directions (horizontal, vertical, diagonal) |
| 32 | const directions = [ |
| 33 | [-1, -1], [-1, 0], [-1, 1], |
| 34 | [0, -1], [0, 1], |
| 35 | [1, -1], [1, 0], [1, 1] |
| 36 | ]; |
| 37 | |
| 38 | // Process each cell in the grid |
| 39 | for (let i = 0; i < rows; i++) { |
| 40 | for (let j = 0; j < cols; j++) { |
| 41 | // Edge Case: Only process empty cells |
| 42 | if (grid[i][j] === ' ') { |
| 43 | let flowerCount = 0; |
| 44 | |
| 45 | // Check all 8 adjacent cells |
| 46 | for (const [dx, dy] of directions) { |
| 47 | const ni = i + dx; |
| 48 | const nj = j + dy; |
| 49 | |
| 50 | // Edge Case: Check if adjacent cell is within bounds |
| 51 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 52 | // Edge Case: Count adjacent flowers |
| 53 | if (grid[ni][nj] === '*') { |
| 54 | flowerCount++; |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // Edge Case: Replace empty cell with count if adjacent flowers exist |
| 60 | if (flowerCount > 0) { |
| 61 | result[i][j] = flowerCount.toString(); |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // Convert arrays back to strings |
| 68 | return result.map(row => row.join('')); |
| 69 | |
| 70 | // Handled Edge Cases: Empty input, input with empty strings, only processing empty cells, checking bounds for adjacent cells, counting adjacent flowers, replacing empty cells with counts |
| 71 | }; |