| 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 - Array of strings representing the flower field where '*' is a flower and ' ' is empty |
| 9 | * @returns {string[]} - Array of strings with empty spaces replaced by flower counts or left empty if no adjacent flowers |
| 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 array |
| 13 | if (input.length === 0) { |
| 14 | return []; |
| 15 | } |
| 16 | |
| 17 | // Edge Case: Handle input with empty strings |
| 18 | const rows = input.length; |
| 19 | const cols = input[0].length; |
| 20 | |
| 21 | // Edge Case: Handle rows with different lengths |
| 22 | // In this implementation, we assume all rows have the same length as the first row |
| 23 | |
| 24 | // Create a result array with the same dimensions as input |
| 25 | const result = Array(rows); |
| 26 | |
| 27 | // Helper function to count adjacent flowers |
| 28 | const countAdjacentFlowers = (r, c) => { |
| 29 | let count = 0; |
| 30 | |
| 31 | // Check all 8 adjacent positions |
| 32 | for (let dr = -1; dr <= 1; dr++) { |
| 33 | for (let dc = -1; dc <= 1; dc++) { |
| 34 | // Skip the current cell |
| 35 | if (dr === 0 && dc === 0) continue; |
| 36 | |
| 37 | const nr = r + dr; |
| 38 | const nc = c + dc; |
| 39 | |
| 40 | // Check if the adjacent position is within bounds |
| 41 | if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) { |
| 42 | // Check if the adjacent position has a flower |
| 43 | if (input[nr][nc] === '*') { |
| 44 | count++; |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | return count; |
| 51 | }; |
| 52 | |
| 53 | // Process each cell in the input |
| 54 | for (let r = 0; r < rows; r++) { |
| 55 | let newRow = ''; |
| 56 | |
| 57 | for (let c = 0; c < cols; c++) { |
| 58 | // If the current cell is a flower, keep it as is |
| 59 | if (input[r][c] === '*') { |
| 60 | newRow += '*'; |
| 61 | } else { |
| 62 | // Count adjacent flowers |
| 63 | const count = countAdjacentFlowers(r, c); |
| 64 | |
| 65 | // If there are no adjacent flowers, leave it empty |
| 66 | // Otherwise, replace with the count |
| 67 | if (count === 0) { |
| 68 | newRow += ' '; |
| 69 | } else { |
| 70 | newRow += count.toString(); |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | result[r] = newRow; |
| 76 | } |
| 77 | |
| 78 | return result; |
| 79 | |
| 80 | // Handled Edge Cases: Empty input array, input with empty strings, rows with different lengths (assumed consistent) |
| 81 | }; |