| 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 | // Edge Case: Handle empty input array |
| 13 | if (!input || input.length === 0) { |
| 14 | return []; |
| 15 | } |
| 16 | |
| 17 | // Edge Case: Handle array with empty string |
| 18 | const rows = input.length; |
| 19 | const cols = input[0] ? input[0].length : 0; |
| 20 | |
| 21 | // Edge Case: Handle rows with different lengths |
| 22 | // We'll process based on the first row's length |
| 23 | |
| 24 | const result = []; |
| 25 | |
| 26 | for (let i = 0; i < rows; i++) { |
| 27 | let newRow = ''; |
| 28 | for (let j = 0; j < cols; j++) { |
| 29 | // Edge Case: Handle when current row is shorter than expected |
| 30 | if (j >= input[i].length) { |
| 31 | newRow += ' '; |
| 32 | continue; |
| 33 | } |
| 34 | |
| 35 | const cell = input[i][j]; |
| 36 | |
| 37 | // If it's a flower, keep it as is |
| 38 | if (cell === '*') { |
| 39 | newRow += '*'; |
| 40 | continue; |
| 41 | } |
| 42 | |
| 43 | // Count adjacent flowers |
| 44 | let count = 0; |
| 45 | |
| 46 | // Check all 8 adjacent positions |
| 47 | for (let di = -1; di <= 1; di++) { |
| 48 | for (let dj = -1; dj <= 1; dj++) { |
| 49 | // Skip the cell itself |
| 50 | if (di === 0 && dj === 0) continue; |
| 51 | |
| 52 | const ni = i + di; |
| 53 | const nj = j + dj; |
| 54 | |
| 55 | // Check bounds |
| 56 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 57 | // Edge Case: Handle when comparing against a shorter row |
| 58 | if (nj < input[ni].length && input[ni][nj] === '*') { |
| 59 | count++; |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // If no adjacent flowers, leave empty, otherwise put the count |
| 66 | if (count === 0) { |
| 67 | newRow += ' '; |
| 68 | } else { |
| 69 | newRow += count.toString(); |
| 70 | } |
| 71 | } |
| 72 | result.push(newRow); |
| 73 | } |
| 74 | |
| 75 | return result; |
| 12 | 76 | }; |
| 77 | |
| 78 | // Handled Edge Cases: empty input array, array with empty string, rows with different lengths, current row shorter than expected |