File size: 11,488 Bytes
d966228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""
Span merger: given a list of valid line numbers and a list of possible spans,
produce a list of output spans that accounts for every line number.

Assignment rules
----------------
Each line number is assigned to the span(s) closest to it:

  distance(line l, span [a, b]) = max(0, a βˆ’ l, l βˆ’ b)
                                = 0     if the line is inside the span,
                                  a βˆ’ l if the line is left  of the span,
                                  l βˆ’ b if the line is right of the span.

A line is assigned to *every* span that achieves the minimum distance.
When a line is equidistant between two adjacent spans both spans claim it
at assignment time.

Tie-breaking at span boundaries
-------------------------------
For a given span's intermediate output [start, end]:
  β€’ start (1st element) – when multiple assigned lines are tied as closest
    to the span's nominal left boundary, the *smallest* is chosen (biased left).
  β€’ end   (2nd element) – when multiple assigned lines are tied as closest
    to the span's nominal right boundary, the *largest* is chosen (biased right).

Because the intermediate boundaries are simply min / max of the assigned
lines these tie-breaking rules are satisfied automatically.

Output normalization
--------------------
The returned spans are normalized after assignment:

  β€’ If two consecutive outputs touch at exactly one duplicated boundary
    point, the earlier span is shrunk so the final output stays disjoint.
  β€’ If candidate spans overlap enough to create a genuine overlap in the
    output, those overlapping outputs are merged.

Special cases
-------------
β€’ Empty line list  β†’ empty output.
β€’ No possible spans β†’ all lines emitted as one ``missing`` span.
β€’ Spans with no lines assigned to them are omitted from the output.
"""

from __future__ import annotations

from typing import TypedDict


class SpanResult(TypedDict):
    start: int
    end: int
    missing: bool


def _distance_to_span(line: int, start: int, end: int) -> int:
    return max(0, start - line, line - end)


def _normalize_spans(possible_spans: list[list[int]]) -> list[tuple[int, int]]:
    normalized: list[tuple[int, int]] = []

    for idx, span in enumerate(possible_spans):
        if len(span) != 2:
            raise ValueError(f"span at index {idx} must contain exactly two integers")

        start, end = span
        if not isinstance(start, int) or not isinstance(end, int):
            raise TypeError(f"span at index {idx} must contain integers")
        if start > end:
            raise ValueError(
                f"span at index {idx} has start > end: [{start}, {end}]"
            )

        normalized.append((start, end))

    return sorted(normalized, key=lambda span: (span[0], span[1]))


def merge_spans(
    line_numbers: list[int],
    possible_spans: list[list[int]],
) -> list[SpanResult]:
    """
    Parameters
    ----------
    line_numbers:
        Unsorted / duplicate-containing list of valid line numbers.
    possible_spans:
        List of [start, end] inclusive span boundaries.

    Returns
    -------
    List of dicts ``{'start': int, 'end': int, 'missing': bool}``,
    ordered by start position.

    Each line is assigned to the span(s) with the smallest
    ``max(0, a βˆ’ l, l βˆ’ b)`` distance. Lines equidistant between two
    adjacent spans are claimed by *both* at assignment time. The final
    returned spans are normalized so the output does not contain a
    duplicated boundary point, and any genuine overlap caused by
    overlapping candidate spans is merged.

    The output start / end of each span is the min / max of its assigned
    lines, which automatically implements the tie-breaking rule:
    start biased toward smaller values, end toward larger values.

    Raises
    ------
    ValueError
        If any span does not contain exactly two integers or if ``start > end``.
    TypeError
        If any span boundary is not an integer.
    """
    sorted_lines = sorted(set(line_numbers))
    spans = _normalize_spans(possible_spans)

    if not sorted_lines:
        return []

    if not spans:
        return [{"start": sorted_lines[0], "end": sorted_lines[-1], "missing": True}]

    assignments: list[list[int]] = [[] for _ in spans]

    for line in sorted_lines:
        min_dist = min(_distance_to_span(line, start, end) for start, end in spans)
        for idx, (start, end) in enumerate(spans):
            if _distance_to_span(line, start, end) == min_dist:
                assignments[idx].append(line)

    output: list[SpanResult] = []
    out_assignments: list[list[int]] = []
    for assigned in assignments:
        if assigned:
            output.append({"start": assigned[0], "end": assigned[-1], "missing": False})
            out_assignments.append(assigned)

    i = 0
    while i < len(output) - 1:
        if output[i]["end"] == output[i + 1]["start"]:
            overlap = output[i]["end"]
            smaller = [line for line in out_assignments[i] if line < overlap]
            if smaller:
                output[i]["end"] = smaller[-1]
                i += 1
            else:
                output.pop(i)
                out_assignments.pop(i)
        else:
            i += 1

    i = 0
    while i < len(output) - 1:
        if output[i]["end"] >= output[i + 1]["start"]:
            output[i] = {
                "start": output[i]["start"],
                "end": max(output[i]["end"], output[i + 1]["end"]),
                "missing": output[i]["missing"] or output[i + 1]["missing"],
            }
            output.pop(i + 1)
        else:
            i += 1

    return output


# --------------------------------------------------------------------------- #
# Formatting helper                                                             #
# --------------------------------------------------------------------------- #

def format_spans(spans: list[SpanResult]) -> str:
    parts = []
    for s in spans:
        tag = f"[{s['start']},{s['end']}]"
        parts.append(tag)
    return "[" + ", ".join(parts) + "]"


# --------------------------------------------------------------------------- #
# Smoke-tests                                                                  #
# --------------------------------------------------------------------------- #

if __name__ == "__main__":
    cases = [
        # ── Original examples ──────────────────────────────────────────── #
        {
            "label": "Example 1 – pre-line absorbed into nearest span; empty span dropped",
            "lines": [1, 3, 5, 6, 7, 8, 9, 10, 12, 15],
            "spans": [[2, 5], [6, 15], [16, 20]],
            "expected": "[[1,5], [6,15]]",
        },
        {
            "label": "Example 2 – line 5 equidistant β†’ prev span end shrunk from 5β†’3",
            "lines": [1, 3, 5, 6, 7, 8, 9, 10, 12, 18],
            "spans": [[2, 4], [6, 14], [16, 20]],
            "expected": "[[1,3], [5,12], [18,18]]",
        },
        # ── Edge cases ─────────────────────────────────────────────────── #
        {
            "label": "EC-01  empty line list β†’ empty output",
            "lines": [],
            "spans": [[1, 5], [6, 10]],
            "expected": "[]",
        },
        {
            "label": "EC-02  no spans β†’ all lines become missing groups",
            # Bug: the old else-branch would double-emit everything.
            "lines": [2, 3, 7, 8],
            "spans": [],
            "expected": "[[2,8]]",
        },
        {
            "label": "EC-03  all lines left of only span β†’ absorbed as nearest",
            "lines": [1, 2, 3],
            "spans": [[10, 20]],
            "expected": "[[1,3]]",
        },
        {
            "label": "EC-04  all lines right of only span β†’ absorbed as nearest",
            "lines": [15, 16, 20],
            "spans": [[1, 10]],
            "expected": "[[15,20]]",
        },
        {
            "label": "EC-05  adjacent spans β†’ each line goes to the span it is inside",
            "lines": [1, 3, 5, 8],
            "spans": [[1, 4], [5, 10]],
            "expected": "[[1,3], [5,8]]",
        },
        {
            "label": "EC-06  duplicate line numbers β†’ deduplicated before processing",
            "lines": [3, 3, 5, 5, 7],
            "spans": [[1, 10]],
            "expected": "[[3,7]]",
        },
        {
            "label": "EC-07  line 7 equidistant β†’ prev span end shrunk from 7β†’3",
            "lines": [3, 7, 11],
            "spans": [[1, 5], [9, 15]],
            "expected": "[[3,3], [7,11]]",
        },
        {
            "label": "EC-08  empty gap β†’ each line assigned to the span it is inside, no overlap",
            "lines": [2, 4, 8, 12],
            "spans": [[1, 5], [7, 15]],
            "expected": "[[2,4], [8,12]]",
        },
        {
            "label": "EC-09  single line, span wider than needed β†’ clipped at line",
            "lines": [5],
            "spans": [[3, 7]],
            "expected": "[[5,5]]",
        },
        {
            "label": "EC-10  line 6 equidistant β†’ prev span end shrunk from 6β†’2",
            "lines": [2, 6, 7, 11, 15],
            "spans": [[1, 4], [8, 12], [14, 20]],
            "expected": "[[2,2], [6,11], [15,15]]",
        },
        {
            "label": "EC-11  single span β†’ all lines (pre and inside) absorbed as nearest",
            "lines": [1, 2, 5, 6, 15],
            "spans": [[10, 20]],
            "expected": "[[1,15]]",
        },
        {
            "label": "EC-12  first span gets no lines; subsequent spans absorb orphans",
            "lines": [3, 8],
            "spans": [[1, 2], [5, 7], [10, 15]],
            "expected": "[[3,3], [8,8]]",
        },
        {
            "label": "EC-13  line 10 equidistant β†’ prev span end shrunk from 10β†’5",
            "lines": [1, 5, 10, 15, 20],
            "spans": [[3, 8], [12, 18]],
            "expected": "[[1,5], [10,20]]",
        },
        {
            "label": "EC-14  overlap where prev span has no smaller line β†’ prev span dropped",
            # line 7 equidistant between [1,5] and [9,15]: both claim it.
            # span 0 assigned=[7] only; no line < 7 exists β†’ span 0 is dropped.
            "lines": [7, 11],
            "spans": [[1, 5], [9, 15]],
            "expected": "[[7,11]]",
        },
        {
            "label": "EC-15  overlapping possible spans β†’ genuine overlap merged in pass 2",
            # spans [1,8] and [3,10] overlap; lines 4 and 6 are inside both β†’
            # both spans claim 4 and 6, so output before pass 2 = [[2,6],[4,9]].
            # pass 1 sees 6 != 4 (strict >), skips; pass 2 merges β†’ [[2,9]].
            "lines": [2, 4, 6, 9],
            "spans": [[1, 8], [3, 10]],
            "expected": "[[2,9]]",
        },
    ]

    for case in cases:
        result = merge_spans(case["lines"], case["spans"])
        formatted = format_spans(result)
        status = "βœ“" if formatted == case["expected"] else "βœ—"
        print(f"{status} {case['label']}")
        print(f"    lines:    {case['lines']}")
        print(f"    spans:    {case['spans']}")
        print(f"    output:   {formatted}")
        print(f"    expected: {case['expected']}")
        print()