File size: 6,177 Bytes
38c016b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env python3
"""
Test to identify the word extension bug where words appear to extend beyond their boundaries.
"""

import sys
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent.parent  # Go up from test-integration to backend-py
sys.path.insert(0, str(project_root))

from src.services.crossword_generator_fixed import CrosswordGeneratorFixed

def debug_word_extension_issue():
    """Debug the specific word extension issue."""
    
    print("🔍 Debugging Word Extension Issue\n")
    
    generator = CrosswordGeneratorFixed(vector_service=None)
    
    # Manually create a scenario that reproduces the issue
    grid = [["." for _ in range(10)] for _ in range(10)]
    placed_words = []
    
    print("Step-by-step placement test:")
    print("=" * 50)
    
    # Step 1: Place COMPUTER horizontally
    print("1. Placing COMPUTER at (4, 0) horizontal")
    if generator._can_place_word(grid, "COMPUTER", 4, 0, "horizontal"):
        generator._place_word(grid, "COMPUTER", 4, 0, "horizontal")
        placed_words.append({
            "word": "COMPUTER", "row": 4, "col": 0, "direction": "horizontal", "number": 1
        })
        print("✅ COMPUTER placed successfully")
        print_grid_section(grid, 2, 7, 0, 10)
    
    # Step 2: Place MACHINE vertically intersecting with C
    print("\n2. Placing MACHINE at (2, 0) vertical")
    if generator._can_place_word(grid, "MACHINE", 2, 0, "vertical"):
        generator._place_word(grid, "MACHINE", 2, 0, "vertical")
        placed_words.append({
            "word": "MACHINE", "row": 2, "col": 0, "direction": "vertical", "number": 2
        })
        print("✅ MACHINE placed successfully")
        print_grid_section(grid, 2, 9, 0, 10)
    
    # Step 3: Try to place EXPERT horizontally
    print("\n3. Testing EXPERT placement at various positions:")
    
    test_positions = [
        (7, 3, "horizontal"),  # This is where the algorithm tried to place it
        (7, 2, "horizontal"),  # This might be where it actually went
        (6, 3, "horizontal"),  # Alternative position
    ]
    
    for row, col, direction in test_positions:
        print(f"   Testing EXPERT at ({row}, {col}) {direction}")
        
        can_place = generator._can_place_word(grid, "EXPERT", row, col, direction)
        print(f"   Can place: {can_place}")
        
        if can_place:
            # Test placement on a copy
            test_grid = [r[:] for r in grid]
            original_state = generator._place_word(test_grid, "EXPERT", row, col, direction)
            
            print("   Grid after placement:")
            print_grid_section(test_grid, 5, 10, 0, 10)
            
            # Check what sequences exist
            sequences = find_all_sequences(test_grid)
            print(f"   All sequences found: {sequences}")
            
            # Restore grid
            generator._remove_word(test_grid, original_state)
            print("   " + "-" * 30)
    
    # Step 4: Test the validation functions directly
    print("\n4. Testing validation functions:")
    print("=" * 50)
    
    # Create a grid with a known extension issue
    test_grid = [["." for _ in range(10)] for _ in range(10)]
    
    # Place COMPUTER
    for i, letter in enumerate("COMPUTER"):
        test_grid[4][i] = letter
    
    # Place MACHINE 
    for i, letter in enumerate("MACHINE"):
        test_grid[2 + i][0] = letter
    
    # Place EXPERT but with an extension issue
    expert_letters = "AEXPERT"  # Simulate the extension issue
    for i, letter in enumerate(expert_letters):
        test_grid[7][2 + i] = letter
    
    print("Test grid with extension issue:")
    print_grid_section(test_grid, 2, 9, 0, 10)
    
    # Test validation
    mock_placed_words = [
        {"word": "COMPUTER", "row": 4, "col": 0, "direction": "horizontal"},
        {"word": "MACHINE", "row": 2, "col": 0, "direction": "vertical"},
        {"word": "EXPERT", "row": 7, "col": 3, "direction": "horizontal"},  # Note: col 3, not 2
    ]
    
    print("\nValidation results:")
    is_valid = generator._validate_final_grid(test_grid, mock_placed_words)
    print(f"Grid validation result: {is_valid}")

def print_grid_section(grid, start_row, end_row, start_col, end_col):
    """Print a section of the grid."""
    print("Grid:")
    for r in range(start_row, min(end_row, len(grid))):
        row_str = f"R{r}: "
        for c in range(start_col, min(end_col, len(grid[0]))):
            if grid[r][c] == ".":
                row_str += ". "
            else:
                row_str += f"{grid[r][c]} "
        print(row_str)

def find_all_sequences(grid):
    """Find all letter sequences in the grid."""
    sequences = []
    
    # Horizontal sequences
    for r in range(len(grid)):
        current_seq = ""
        start_col = None
        
        for c in range(len(grid[0])):
            if grid[r][c] != ".":
                if start_col is None:
                    start_col = c
                current_seq += grid[r][c]
            else:
                if current_seq and len(current_seq) > 1:
                    sequences.append(f"H({r},{start_col}): {current_seq}")
                current_seq = ""
                start_col = None
        
        # Handle end of row
        if current_seq and len(current_seq) > 1:
            sequences.append(f"H({r},{start_col}): {current_seq}")
    
    # Vertical sequences
    for c in range(len(grid[0])):
        current_seq = ""
        start_row = None
        
        for r in range(len(grid)):
            if grid[r][c] != ".":
                if start_row is None:
                    start_row = r
                current_seq += grid[r][c]
            else:
                if current_seq and len(current_seq) > 1:
                    sequences.append(f"V({start_row},{c}): {current_seq}")
                current_seq = ""
                start_row = None
        
        # Handle end of column
        if current_seq and len(current_seq) > 1:
            sequences.append(f"V({start_row},{c}): {current_seq}")
    
    return sequences

if __name__ == "__main__":
    debug_word_extension_issue()