| 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 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 | for (let i = 0; i < rows; i++) { |
| 23 | if (input[i].length !== cols) { |
| 24 | throw new Error('All rows must have the same length'); |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | // Create a result grid as a 2D array |
| 29 | const result = Array(rows); |
| 30 | for (let i = 0; i < rows; i++) { |
| 31 | result[i] = input[i].split(''); |
| 32 | } |
| 33 | |
| 34 | // Define the 8 possible directions (horizontal, vertical, diagonal) |
| 35 | const directions = [ |
| 36 | [-1, -1], [-1, 0], [-1, 1], |
| 37 | [0, -1], [0, 1], |
| 38 | [1, -1], [1, 0], [1, 1] |
| 39 | ]; |
| 40 | |
| 41 | // For each cell in the grid |
| 42 | for (let row = 0; row < rows; row++) { |
| 43 | for (let col = 0; col < cols; col++) { |
| 44 | // If the cell is empty, count adjacent flowers |
| 45 | if (input[row][col] === ' ') { |
| 46 | let count = 0; |
| 47 | |
| 48 | // Check all 8 directions |
| 49 | for (const [dx, dy] of directions) { |
| 50 | const newRow = row + dx; |
| 51 | const newCol = col + dy; |
| 52 | |
| 53 | // Edge Case: Check bounds to avoid accessing invalid indices |
| 54 | if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) { |
| 55 | if (input[newRow][newCol] === '*') { |
| 56 | count++; |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // Edge Case: Only replace empty cell with count if count > 0 |
| 62 | if (count > 0) { |
| 63 | result[row][col] = count.toString(); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // Convert each row back to a string |
| 70 | return result.map(row => row.join('')); |
| 12 | 71 | }; |
| 72 | |
| 73 | // Handled Edge Cases: Empty input array, input with empty strings, rows with different lengths, invalid indices when checking neighbors, empty cells with zero adjacent flowers |