| 4 | 4 | // |
| 5 | 5 | |
| 6 | 6 | /** |
| 7 | | * @param {string[]} input |
| 8 | | * @returns {string[]} |
| 7 | * Annotates a flower field grid by replacing empty spaces with the count of adjacent flowers. |
| 8 | * @param {string[]} input - Array of strings representing the flower field grid ('*' for flower, ' ' for 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 | const rows = input.length; |
| 18 | const cols = input[0].length; |
| 19 | |
| 20 | // Edge Case: Handle rows with different lengths |
| 21 | for (let i = 0; i < rows; i++) { |
| 22 | if (input[i].length !== cols) { |
| 23 | throw new Error('All rows must have the same length'); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | // Create a result grid as a 2D array |
| 28 | const result = Array(rows).fill().map(() => Array(cols).fill('')); |
| 29 | |
| 30 | // Define the 8 possible directions (horizontal, vertical, diagonal) |
| 31 | const directions = [ |
| 32 | [-1, -1], [-1, 0], [-1, 1], |
| 33 | [0, -1], [0, 1], |
| 34 | [1, -1], [1, 0], [1, 1] |
| 35 | ]; |
| 36 | |
| 37 | // Iterate through each cell in the grid |
| 38 | for (let row = 0; row < rows; row++) { |
| 39 | for (let col = 0; col < cols; col++) { |
| 40 | // If the cell is a flower, keep it as is |
| 41 | if (input[row][col] === '*') { |
| 42 | result[row][col] = '*'; |
| 43 | } else { |
| 44 | // Count adjacent flowers |
| 45 | let flowerCount = 0; |
| 46 | |
| 47 | // Check all 8 directions |
| 48 | for (const [dx, dy] of directions) { |
| 49 | const newRow = row + dx; |
| 50 | const newCol = col + dy; |
| 51 | |
| 52 | // Edge Case: Check if the adjacent cell is within bounds |
| 53 | if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) { |
| 54 | if (input[newRow][newCol] === '*') { |
| 55 | flowerCount++; |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // If no adjacent flowers, leave empty, otherwise put the count |
| 61 | result[row][col] = flowerCount === 0 ? ' ' : flowerCount.toString(); |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | // Convert the 2D array back to an array of strings |
| 67 | return result.map(row => row.join('')); |
| 12 | 68 | }; |
| 69 | |
| 70 | // Handled Edge Cases: Empty input array, rows with different lengths, adjacent cells out of bounds |