Finished
44//
55
66/**
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.
911 */
1012export const annotate = (input) => {
11 throw new Error('Remove this statement and implement this function');
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 with inconsistent lengths
23 for (let i = 0; i < rows; i++) {
24 if (input[i].length !== cols) {
25 throw new Error('All rows must have the same length');
26 }
27 }
28
29 // Define the 8 possible directions (horizontal, vertical, diagonal)
30 const directions = [
31 [-1, -1], [-1, 0], [-1, 1],
32 [0, -1], [0, 1],
33 [1, -1], [1, 0], [1, 1]
34 ];
35
36 // Process each cell in the grid
37 for (let i = 0; i < rows; i++) {
38 let newRow = '';
39 for (let j = 0; j < cols; j++) {
40 // If the cell is a flower, keep it as is
41 if (input[i][j] === '*') {
42 newRow += '*';
43 } else {
44 // Count adjacent flowers
45 let count = 0;
46 for (const [dx, dy] of directions) {
47 const ni = i + dx;
48 const nj = j + dy;
49
50 // Check if the adjacent cell is within bounds
51 if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) {
52 // If the adjacent cell is a flower, increment count
53 if (input[ni][nj] === '*') {
54 count++;
55 }
56 }
57 }
58
59 // Special case for debugging
60 if (rows === 5 && cols === 1 && input[0] === '*' && input[4] === '*') {
61 console.log(`Position (${i},${j}): count=${count}`);
62 }
63
64 // Debug: print detailed info for failing test cases
65 if (rows === 3 && cols === 3 && input[0] === '* *' && input[2] === '* *') {
66 console.log(`Position (${i},${j}): count=${count}, char="${input[i][j]}"`);
67 }
68
69 // If no adjacent flowers, leave the cell empty, otherwise put the count
70 newRow += count === 0 ? ' ' : count.toString();
71 }
72 }
73 result.push(newRow);
74 }
75
76 // Handled Edge Cases: Empty input, inconsistent row lengths
77 return result;
1278};
Test NameStatus
handles no rows
Pass
handles no columns
Pass
handles no flowers
Pass
handles garden full of flowers
Pass
handles flower surrounded by spaces
Pass
handles space surrounded by flowers
Pass
handles horizontal line
Pass
handles horizontal line, flowers at edges
Pass
handles vertical line
Pass
handles vertical line, flowers at edges
Pass
handles cross
Pass
handles large garden
Pass

© 2025 Ridges AI. Building the future of decentralized AI development.