| 1 | | // |
| 2 | | // This is only a SKELETON file for the 'Flower Field' exercise. It's been provided as a |
| 3 | | // convenience to get you started writing code faster. |
| 4 | | // |
| 5 | | |
| 6 | | /** |
| 7 | | * @param {string[]} input |
| 8 | | * @returns {string[]} |
| 9 | | */ |
| 10 | 1 | export const annotate = (input) => { |
| 11 | | throw new Error('Remove this statement and implement this function'); |
| 12 | | }; |
| 2 | // Edge Case: Handle empty input array |
| 3 | if (!input || input.length === 0) { |
| 4 | return []; |
| 5 | } |
| 6 | |
| 7 | const rows = input.length; |
| 8 | const cols = input[0].length; |
| 9 | |
| 10 | // Edge Case: Handle rows with different lengths |
| 11 | for (let i = 0; i < rows; i++) { |
| 12 | if (input[i].length !== cols) { |
| 13 | throw new Error('All rows must have the same length'); |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | // Convert input strings to arrays for easier manipulation |
| 18 | const originalGrid = input.map(row => row.split('')); |
| 19 | const resultGrid = input.map(row => row.split('')); |
| 20 | |
| 21 | // Define the 8 possible directions (horizontal, vertical, diagonal) |
| 22 | const directions = [ |
| 23 | [-1, -1], [-1, 0], [-1, 1], |
| 24 | [0, -1], [0, 1], |
| 25 | [1, -1], [1, 0], [1, 1] |
| 26 | ]; |
| 27 | |
| 28 | // Process each cell in the grid |
| 29 | for (let i = 0; i < rows; i++) { |
| 30 | for (let j = 0; j < cols; j++) { |
| 31 | // Only process empty cells |
| 32 | if (originalGrid[i][j] === ' ') { |
| 33 | let count = 0; |
| 34 | |
| 35 | // Check all 8 adjacent cells using the original grid |
| 36 | for (const [dx, dy] of directions) { |
| 37 | const ni = i + dx; |
| 38 | const nj = j + dy; |
| 39 | |
| 40 | // Edge Case: Check bounds to avoid accessing invalid indices |
| 41 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 42 | if (originalGrid[ni][nj] === '*') { |
| 43 | count++; |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // Edge Case: Only replace empty cell with count if count > 0 |
| 49 | if (count > 0) { |
| 50 | resultGrid[i][j] = count.toString(); |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Convert arrays back to strings |
| 57 | return resultGrid.map(row => row.join('')); |
| 58 | }; |