| 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'); |
| 12 | | }; |
| 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 of different lengths by treating them as if they have trailing spaces |
| 23 | // This is implicitly handled by always using cols = input[0].length and checking bounds |
| 24 | |
| 25 | for (let i = 0; i < rows; i++) { |
| 26 | let newRow = ''; |
| 27 | for (let j = 0; j < cols; j++) { |
| 28 | const current = input[i][j]; |
| 29 | |
| 30 | // If the current cell is a flower, keep it as is |
| 31 | if (current === '*') { |
| 32 | newRow += '*'; |
| 33 | continue; |
| 34 | } |
| 35 | |
| 36 | // Count adjacent flowers |
| 37 | let count = 0; |
| 38 | |
| 39 | // Check all 8 adjacent cells |
| 40 | for (let di = -1; di <= 1; di++) { |
| 41 | for (let dj = -1; dj <= 1; dj++) { |
| 42 | // Skip the cell itself |
| 43 | if (di === 0 && dj === 0) continue; |
| 44 | |
| 45 | const ni = i + di; |
| 46 | const nj = j + dj; |
| 47 | |
| 48 | // Check if the adjacent cell is within bounds |
| 49 | // Edge Case: Handle out-of-bounds cells (treat as empty) |
| 50 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 51 | if (input[ni][nj] === '*') { |
| 52 | count++; |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // If no adjacent flowers, leave the cell empty |
| 59 | // Otherwise, replace with the count |
| 60 | if (count === 0) { |
| 61 | newRow += ' '; |
| 62 | } else { |
| 63 | newRow += count.toString(); |
| 64 | } |
| 65 | } |
| 66 | result.push(newRow); |
| 67 | } |
| 68 | |
| 69 | return result; |
| 70 | |
| 71 | // Handled Edge Cases: Empty input, rows of different lengths, out-of-bounds cells |
| 72 | }; |