Algorithm Search⌘K

Algorithmcore

Patience diff

Also called patience diff algorithm.

Match equal first and last lines, then the lines that occur once in both files by a longest increasing subsequence, and diff each gap between them again.

Time
O(n^2 log n) expected
Space
O(n) extra
Where
n = the total number of lines in both files
Properties
not adaptivedeterministicofflinerecursive

Patience diff compares two files line by line. It first matches the equal lines at the start and at the end. Then it takes only the lines that occur exactly once in each file, matches as many of them as it can in order, and diffs each gap between two matched lines in the same way. The matched unique lines are found as a longest increasing subsequence, by patience sorting, which gives the method its name. Bram Cohen described it. The result is not always a shortest edit script, as from Myers' algorithm, but it often reads better, because it does not align unrelated code on common lines such as braces and blank lines. Heckel's algorithm also starts from unique lines, but it does not recurse, and it reports moves.

In plain words

Two versions of a file usually start the same and end the same, so match those lines first.

In the middle part, look for lines that occur only once in each version. Such a line, for example the name of a function, is a safe anchor. The anchors may disagree on the order, so keep the largest set of them that is in the same order in both versions.

Between two anchors there is a smaller middle part. Do the same steps there. A line can be rare in a small part even if it is common in the whole file. When a part has no anchor at all, either stop or use an ordinary diff for that part.

The problem

The input is an old file AA and a new file BB, as sequences of lines with an equality test and a hash of a line. The output is a matching, a set of pairs (i,j)(i, j) with A[i]=B[j]A[i] = B[j] that increase in both files, and the edit script that keeps the matched lines, deletes the other old lines and inserts the other new lines. The goal is a diff that a person can read, in which the kept lines are the lines that really stayed. The length of the matching is not the goal: a longest one is a longest common subsequence, and it can keep a closing brace of one function and give it to another.

The algorithm

The pseudocode uses half-open ranges: MATCH works on the old lines A[alo…ahi−1]A[alo \ldots ahi - 1] and the new lines B[blo…bhi−1]B[blo \ldots bhi - 1]. The fallback is a choice. Without it, a range with no anchor stays unmatched, as in Cohen's steps; with it, the range is matched by an ordinary diff, as Git does. The implementation of this page uses the dynamic program for a longest common subsequence as the fallback.

  1. PATIENCE(A, B)
  2. 1M ← an empty list; MATCH(1, |A| + 1, 1, |B| + 1)
  3. MATCH(alo, ahi, blo, bhi)
  4. 2while alo < ahi, blo < bhi and A[alo] = B[blo] do append (alo, blo) to M; alo ← alo + 1; blo ← blo + 1 ▷ step 1
  5. 3T ← empty; while alo < ahi, blo < bhi and A[ahi - 1] = B[bhi - 1] do ahi ← ahi - 1; bhi ← bhi - 1; put (ahi, bhi) at the front of T ▷ step 2
  6. 4S ← a longest subsequence, increasing in j, of the pairs (i, j) in order of i whose line occurs once in A[alo .. ahi - 1] and once in B[blo .. bhi - 1] ▷ step 3
  7. 5if S is empty then append the matching of FALLBACK(alo, ahi, blo, bhi) to M, which may be no pairs
  8. 6else for each (i, j) in S in order do MATCH(alo, i, blo, j); append (i, j) to M; alo ← i + 1; blo ← j + 1
  9. MATCH(alo, ahi, blo, bhi) ▷ step 4: the gap after the last anchor
  10. 7append T to M
  11. 8return the script that keeps the pairs of M

Line L4 counts the lines of each side of the range in a hash table and keeps the lines with count 1 on both sides. Sorted by their old line number, these pairs form a sequence of new line numbers, and a longest increasing subsequence of it is the largest set of anchors that do not cross. Patience sorting finds it with one binary search per pair. Line L6 then calls MATCH on each gap: the gap before the first anchor, the gaps between two anchors and, after the loop, the gap after the last anchor. In a gap, line L4 counts again, so a line that occurs twice in the files but once in the gap becomes an anchor there.

Example

A function is inserted between two others.

line old AA new BB
1 void func1() { void func1() {
2 x += 1 x += 1
3 } }
4 (blank) (blank)
5 void func2() { void functhreehalves() {
6 x += 2 x += 1.5
7 } }
8 (blank)
9 void func2() {
10 x += 2
11 }

Line L2 matches the first four lines. Line L3 matches the last three lines: } with }, x += 2 with x += 2, and void func2() { with void func2() {. The remaining range is empty in AA and holds new lines 5 to 8 in BB, so line L4 finds no pair, and the four lines are inserted. The diff shows the new function as one block:

 void func1() {
     x += 1
 }

+void functhreehalves() {
+    x += 1.5
+}
+
 void func2() {
     x += 2
 }

A longest common subsequence has 7 lines, and the matching above is one. Another one, just as long, matches the old } and blank line of func1 with new lines 7 and 8, the ones of the new function. Its diff inserts the lines "}", blank, "void functhreehalves() {" and "x += 1.5" after "x += 1", so the new function looks split across the old one. Cohen's post shows that a standard diff can print this second form. A method that only makes the script short has no reason to prefer the first form.

The second example shows the counts in a gap. Take A=[a,b,U,b,a]A = [a, b, U, b, a] and B=[b,a,U,a,b]B = [b, a, U, a, b]. The first lines differ and the last lines differ. In the whole files only UU occurs once on each side, so it is the only anchor, and line L6 calls MATCH on the two gaps. In the gap before UU, both aa and bb now occur once on each side. Their pairs are (1,2)(1, 2) and (2,1)(2, 1), which cross, so line L4 keeps one, the pair (2,1)(2, 1) that patience sorting returns. The gap after UU gives (5,4)(5, 4) in the same way. The matching has 3 pairs.

Correctness

The proof file shows two results. First, each call of MATCH appends only pairs of equal lines inside its range, in increasing order, and each recursive call is on a smaller range; so the method stops, MM is a matching, and the script turns AA into BB. Second, when no line occurs twice in AA and no line occurs twice in BB, the result is a longest common subsequence: matching equal first lines and equal last lines never loses length, every common line in the inner range is unique on both sides, line L4 takes a longest increasing set of them, and no gap can hold another common pair, since it would make that set longer. With repeated lines the result can be shorter than the optimum, and the script longer than a shortest one.

Proof: Patience diff returns a matching of equal lines, and a longest one when no line repeatsfull

We use the pseudocode of the page, with half-open ranges: a call MATCH works on the old lines A[alo…ahi−1]A[alo \ldots ahi - 1] and the new lines B[blo…bhi−1]B[blo \ldots bhi - 1]. A matching of the range is a set of pairs (i,j)(i, j) with A[i]=B[j]A[i] = B[j] inside the range, such that for two pairs (i,j)(i, j) and (i′,j′)(i', j') we have i<i′i < i' if and only if j<j′j < j'. Its length is its number of pairs.

Lemma 1 (each call is local and ordered). A call MATCH on a range appends to MM only pairs inside the range, and the pairs that it appends form a matching of the range, appended in increasing order.

Proof. By induction on the size (ahi−alo)+(bhi−blo)(ahi - alo) + (bhi - blo) of the range. Line L2 appends pairs (alo,blo),(alo+1,blo+1),…(alo, blo), (alo + 1, blo + 1), \ldots of equal lines from the start of the range, and moves the start past them. Line L3 takes pairs of equal lines from the end of the range and moves the end before them; line L7 appends them after everything else, in increasing order. Between these two parts lies the inner range, and all later pairs of the call are inside it. Line L4 takes pairs of equal lines inside the inner range, and line L5 keeps a subset SS that increases in both coordinates. If SS is empty, the fallback appends nothing, or a longest matching of the inner range, which is in order. Otherwise line L6 visits SS in order: before the anchor (i,j)(i, j) it calls MATCH on the gap between the previous anchor and (i,j)(i, j), then appends (i,j)(i, j), and at the end it calls MATCH on the gap after the last anchor. Each gap is inside the inner range and is strictly smaller than the range of the call, since it leaves out at least the anchor. By induction, each gap call appends a matching of its gap, in order. The gaps come one after the other in both files, separated by the anchors, so all the pairs appended are in increasing order in both coordinates. □\square

Theorem 1 (a valid diff). PATIENCE terminates and returns a matching of AA and BB, and the script of line L8 turns AA into BB.

Proof. Each recursive call is on a strictly smaller range, so the recursion is finite, and each call does a finite amount of work. By Lemma 1 applied to the whole range, MM is a matching of AA and BB. The helper matching_to_script keeps the pairs of MM, deletes the other old lines and inserts the other new lines in order, so applying the script to AA gives BB. □\square

Lemma 2 (equal first lines). If A[alo]=B[blo]A[alo] = B[blo], some longest matching of the range contains the pair (alo,blo)(alo, blo). The same holds for the last lines.

Proof. Take a longest matching PP. If neither aloalo nor bloblo is in a pair of PP, add (alo,blo)(alo, blo): every other pair is after it in both files, so PP grows, which is not possible. If aloalo is in the pair (alo,j)(alo, j) and bloblo is in no pair, replace (alo,j)(alo, j) with (alo,blo)(alo, blo); it has equal lines, and since blo≤jblo \le j the order is kept. The case of bloblo alone is the same. If (alo,j)(alo, j) and (i,blo)(i, blo) are both in PP and differ, then alo<ialo < i and j>bloj > blo, so the two pairs cross, which a matching does not allow. So the only remaining case is (alo,blo)∈P(alo, blo) \in P. The last lines are symmetric. □\square

Theorem 2 (no repeated lines). If no line occurs twice in AA and no line occurs twice in BB, then MM is a longest common subsequence of AA and BB, and the script is a shortest edit script, with or without the fallback.

Proof. We show that each call appends a longest matching of its range, by induction on the size of the range. By Lemma 2 used once for each step of line L2 and line L3, a longest matching of the range consists of the pairs of these lines plus a longest matching of the inner range. In the inner range, a pair (i,j)(i, j) with A[i]=B[j]A[i] = B[j] has a line that occurs only once in each file, so also only once in each side of the inner range: line L4 finds every such pair, and only such pairs. A matching of the inner range is then a subset of these pairs that increases in both coordinates, and line L5 takes a longest one, SS. If SS is empty, there is no pair in the inner range, and nothing more is possible. Otherwise, a gap of line L6 contains no pair with equal lines: such a pair would lie in both files strictly between two consecutive anchors of SS, or before the first or after the last, so adding it to SS would give a longer increasing set of pairs. So the gap calls append nothing, and the call appends a longest matching. For the whole range this gives a longest common subsequence, and the script of a longest matching has the least number ∣A∣+∣B∣−2∣M∣|A| + |B| - 2|M| of operations. □\square

The result is not always minimal. With repeated lines the anchors can block a longer matching. For A=[u,a,a,a,v]A = [u, a, a, a, v] and B=[a,a,a,u,v]B = [a, a, a, u, v], line L3 matches vv, and line L4 finds only uu, the single line that occurs once on each side of the inner range. The anchor (1,4)(1, 4), in the numbering from 1, leaves a gap before it that is empty in AA and a gap after it that is empty in BB, so nothing more is matched, and the script has 6 operations. The matching a,a,a,va, a, a, v gives 2.

Cost. One call on a range of ss lines in total counts the lines with a hash table, in O(s)O(s) expected time, sorts the unique pairs, and finds SS with patience piles and binary search, in O(slog⁡s)O(s \log s) time. Every call other than a call without anchors appends at least one anchor, and each line is an anchor at most once, so there are at most n+1n + 1 calls with anchors and at most 2n+22n + 2 calls in total, each on at most nn lines. This gives the bound O(n2log⁡n)O(n^2 \log n) expected. When no line repeats, the proof of Theorem 2 shows that the gap calls find no pairs, so the work is one top call of O(nlog⁡n)O(n \log n) plus calls on gaps that are disjoint, which is O(nlog⁡n)O(n \log n) in total.

Complexity

Count in the word-RAM, with nn the total number of lines of both files, and a hash table with O(1)O(1) expected time per operation.

  • One call. A range with ss lines in total costs O(s)O(s) expected time to count, and O(slog⁡s)O(s \log s) to sort the unique pairs and to find the longest increasing subsequence.
  • No repeated lines. The top call costs O(nlog⁡n)O(n \log n). The gap calls find no pairs and do not recurse, and the gaps are disjoint, so the total is O(nlog⁡n)O(n \log n) expected.
  • Worst case. Every call with anchors appends at least one anchor, and a line is an anchor at most once, so there are at most about 2n2n calls, each on at most nn lines: O(n2log⁡n)O(n^2 \log n) expected. The fallback adds its own cost; the dynamic program of this page costs the product of the sizes of the two sides of each range where it runs, at most O(n2)O(n^2) in total, since those ranges are disjoint.
  • Files that are almost equal. Lines L2 and L3 match the common start and end in linear time, so a small change in a large file costs little beyond one pass.
  • Space. The table, the piles and MM need O(n)O(n), and the recursion is at most O(n)O(n) deep.

Properties

  • Not minimal. The matching can be shorter than a longest common subsequence when lines repeat, so the script can have more operations than a shortest one.
  • Anchors on rare lines. Matches come from lines that are unique in their range, which in source code are often declarations and statements with names, not braces or blank lines.
  • No moves. The output is an ordinary edit script. Anchors that cross are dropped, not reported as moves.
  • Local counts. Counting again in each gap finds anchors that are not unique in the whole files.

Variants and improvements

  • The fallback. Without a fallback, ranges with no unique line stay as one delete and insert block. Git runs its ordinary Myers diff in such ranges.
  • Histogram diff. Histogram diff extends the idea to lines with few copies, and uses a line with the lowest count in the range as the anchor, so it still works when no line is unique.
  • Heckel's passes. Heckel's algorithm also starts from the unique lines, extends them to equal neighbors, keeps crossing links as moves, and does not recurse.
  • Merges. A three-way merge such as diff3 needs two diffs against a base. With a diff that keeps the structure of the code, the conflicts it reports fall at more natural places.

When to use it

Use it for diffs that people read, especially of source code, where a minimum diff can align braces and blank lines of unrelated functions. Git gives it as the option --patience. Do not use it when the shortest script is required, for example to compute an edit distance; use Myers' algorithm or the Hunt-Szymanski algorithm for that.

Pitfalls

  • No unique lines. Files made mostly of repeated lines, such as tables of equal rows, have few anchors. Without a fallback, large ranges stay unmatched.
  • Counts per range. The counts of line L4 must be taken in the current range, not in the whole files, or the recursion finds no new anchors.
  • Crossing anchors. Keeping all unique pairs gives an invalid script when a block moved. Only an increasing subset can be kept.
  • Steps 1 and 2 matter. Equal first and last lines that are not unique, such as a closing brace at the end of the file, are matched only by lines L2 and L3. A version without these steps leaves them to the fallback.
  • Recursion depth. The depth can grow with the number of lines. An implementation in a language with a small call stack should use an explicit stack.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

patience_diff.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/patience-diff/. The authors are listed in prov/3MB06K.jsonl.
"""Patience diff, after the four steps of Bram Cohen's description (2010).

The old file is a and the new file is b. A range of the problem is a pair of
half-open slices a[alo:ahi] and b[blo:bhi]. In each range the method matches
equal first lines, then equal last lines, then the lines that occur exactly once
in each side of the range, keeping a longest increasing subset of those, and it
runs again in each gap between two kept lines. If a range has no unique common
line, the fallback decides: None leaves the range unmatched, and "lcs" matches it
with the dynamic program of the shared helper, as Git falls back to Myers' method.
"""

from bisect import bisect_left
from collections.abc import Hashable, Sequence

from txdiff import Op, lcs_matching, matching_to_script


def longest_increasing(pairs: Sequence[tuple[int, int]]) -> list[tuple[int, int]]:
    """Return a longest subsequence of pairs whose second coordinates increase, by patience sorting.

    The pairs are sorted by their first coordinate, and the second coordinates are distinct.
    Each pair goes on the leftmost pile whose top is larger, and keeps a link to the top
    of the pile on its left; the links from the top of the last pile give the result.
    """
    tops: list[int] = []
    top_index: list[int] = []
    back = [-1] * len(pairs)
    for t, (_, j) in enumerate(pairs):
        p = bisect_left(tops, j)
        back[t] = top_index[p - 1] if p > 0 else -1
        if p == len(tops):
            tops.append(j)
            top_index.append(t)
        else:
            tops[p] = j
            top_index[p] = t
    out: list[tuple[int, int]] = []
    t = top_index[-1] if top_index else -1
    while t >= 0:
        out.append(pairs[t])
        t = back[t]
    out.reverse()
    return out


def unique_common(a: Sequence[Hashable], b: Sequence[Hashable],
                  alo: int, ahi: int, blo: int, bhi: int) -> list[tuple[int, int]]:
    """Return the pairs (i, j), sorted by i, of lines that occur once in a[alo:ahi] and once in b[blo:bhi]."""
    where: dict[Hashable, list[int]] = {}  # line -> [count in a, index in a, count in b, index in b]
    for i in range(alo, ahi):
        e = where.setdefault(a[i], [0, -1, 0, -1])
        e[0] += 1
        e[1] = i
    for j in range(blo, bhi):
        e = where.get(b[j])
        if e is not None:
            e[2] += 1
            e[3] = j
    return sorted((e[1], e[3]) for e in where.values() if e[0] == 1 and e[2] == 1)


def patience_matching(a: Sequence[Hashable], b: Sequence[Hashable],
                      fallback: str | None = None) -> list[tuple[int, int]]:
    """Return the matching (i, j) of patience diff, increasing in both coordinates."""
    if fallback not in (None, "lcs"):
        raise ValueError("fallback must be None or 'lcs'")
    pairs: list[tuple[int, int]] = []  # @line L1

    def match(alo: int, ahi: int, blo: int, bhi: int) -> None:
        while alo < ahi and blo < bhi and a[alo] == b[blo]:  # @line L2
            pairs.append((alo, blo))
            alo, blo = alo + 1, blo + 1
        tail: list[tuple[int, int]] = []
        while alo < ahi and blo < bhi and a[ahi - 1] == b[bhi - 1]:  # @line L3
            ahi, bhi = ahi - 1, bhi - 1
            tail.append((ahi, bhi))
        anchors = longest_increasing(unique_common(a, b, alo, ahi, blo, bhi))  # @line L4
        if not anchors:  # @line L5
            if fallback == "lcs" and alo < ahi and blo < bhi:
                pairs.extend((alo + i, blo + j) for i, j in lcs_matching(a[alo:ahi], b[blo:bhi]))
        else:
            for i, j in anchors:  # @line L6
                match(alo, i, blo, j)
                pairs.append((i, j))
                alo, blo = i + 1, j + 1
            match(alo, ahi, blo, bhi)
        pairs.extend(reversed(tail))  # @line L7

    match(0, len(a), 0, len(b))
    return pairs


def patience_diff(a: Sequence[Hashable], b: Sequence[Hashable], fallback: str | None = None) -> list[Op]:
    """Return the edit script from a to b that keeps the patience matching."""
    return matching_to_script(a, b, patience_matching(a, b, fallback))  # @line L8
txdiff.py 221 lines
# SPDX-License-Identifier: MIT
# Shared helper of the text processing and typesetting pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Common parts of the diff and merge pages: lines, edit scripts, the LCS matcher and a unified diff printer.

An edit script turns a sequence a into a sequence b. It is a list of Op values in
order. Each Op has a kind, an index i into a, an index j into b, and the item:

- Op(KEEP, i, j, a[i]): a[i] is kept, and it is b[j];
- Op(DELETE, i, j, a[i]): a[i] is deleted; j is the number of items of b made so far;
- Op(INSERT, i, j, b[j]): b[j] is inserted; i is the number of items of a used so far.

A matching is a list of pairs (i, j), increasing in both coordinates, of items
that the script keeps. The named algorithms of the pages are not in this file.
"""

from collections.abc import Callable, Sequence
from typing import Any, NamedTuple

KEEP = "="
DELETE = "-"
INSERT = "+"


class Op(NamedTuple):
    kind: str
    i: int
    j: int
    item: Any


def split_lines(text: str) -> list[str]:
    """Split text at each "\\n" into lines without the line feed; a final line feed adds no empty line."""
    if text == "":
        return []
    lines = text.split("\n")
    if lines[-1] == "":
        lines.pop()
    return lines


def is_matching(a: Sequence[Any], b: Sequence[Any], pairs: Sequence[tuple[int, int]],
                eq: Callable[[Any, Any], bool] | None = None) -> bool:
    """Return True if pairs is strictly increasing in both coordinates and each pair is equal by eq."""
    eq = eq if eq is not None else (lambda x, y: x == y)
    pi, pj = -1, -1
    for i, j in pairs:
        if not (pi < i < len(a) and pj < j < len(b)) or not eq(a[i], b[j]):
            return False
        pi, pj = i, j
    return True


def lcs_matching(a: Sequence[Any], b: Sequence[Any],
                 eq: Callable[[Any, Any], bool] | None = None) -> list[tuple[int, int]]:
    """Return a longest matching of a and b by the O(n m) dynamic program.

    eq(x, y) decides whether x and y may be matched; the default is ==. Ties go to
    the earliest pair, so the result is fixed for given inputs.
    """
    eq = eq if eq is not None else (lambda x, y: x == y)
    n, m = len(a), len(b)
    # length[i][j] is the length of a longest matching of a[i:] and b[j:].
    length = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(n - 1, -1, -1):
        row, below = length[i], length[i + 1]
        ai = a[i]
        for j in range(m - 1, -1, -1):
            if eq(ai, b[j]):
                row[j] = below[j + 1] + 1
            else:
                row[j] = below[j] if below[j] >= row[j + 1] else row[j + 1]
    pairs: list[tuple[int, int]] = []
    i = j = 0
    while i < n and j < m:
        if eq(a[i], b[j]):
            pairs.append((i, j))
            i += 1
            j += 1
        elif length[i + 1][j] >= length[i][j + 1]:
            i += 1
        else:
            j += 1
    return pairs


def matching_to_script(a: Sequence[Any], b: Sequence[Any], pairs: Sequence[tuple[int, int]]) -> list[Op]:
    """Return the edit script that keeps the pairs; in each gap the deletes come before the inserts."""
    script: list[Op] = []
    i = j = 0
    for pi, pj in list(pairs) + [(len(a), len(b))]:
        if pi < i or pj < j:
            raise ValueError("the pairs are not increasing")
        while i < pi:
            script.append(Op(DELETE, i, j, a[i]))
            i += 1
        while j < pj:
            script.append(Op(INSERT, i, j, b[j]))
            j += 1
        if pi < len(a) and pj < len(b):
            script.append(Op(KEEP, i, j, a[i]))
            i += 1
            j += 1
    return script


def script_matching(script: Sequence[Op]) -> list[tuple[int, int]]:
    """Return the pairs (i, j) that the script keeps."""
    return [(op.i, op.j) for op in script if op.kind == KEEP]


def apply_script(a: Sequence[Any], script: Sequence[Op]) -> list[Any]:
    """Apply the script to a and return the new sequence; raise ValueError if the script does not fit a."""
    out: list[Any] = []
    i = 0
    for op in script:
        if op.kind == INSERT:
            if op.i != i or op.j != len(out):
                raise ValueError(f"bad insert {op}")
            out.append(op.item)
        elif op.kind in (KEEP, DELETE):
            if op.i != i or i >= len(a) or op.item != a[i] or op.j != len(out):
                raise ValueError(f"bad {op.kind} {op}")
            if op.kind == KEEP:
                out.append(a[i])
            i += 1
        else:
            raise ValueError(f"unknown kind {op.kind!r}")
    if i != len(a):
        raise ValueError("the script does not use all of a")
    return out


def is_valid_script(a: Sequence[Any], b: Sequence[Any], script: Sequence[Op]) -> bool:
    """Return True if the script fits a and turns a into b."""
    try:
        return apply_script(a, script) == list(b)
    except ValueError:
        return False


def script_cost(script: Sequence[Op]) -> int:
    """Return the number of deletes and inserts of the script."""
    return sum(1 for op in script if op.kind != KEEP)


def _opcodes(script: Sequence[Op]) -> list[tuple[str, int, int, int, int]]:
    """Group the script into runs in the format of difflib: equal, delete, insert or replace."""
    codes: list[tuple[str, int, int, int, int]] = []
    i = j = 0
    k = 0
    while k < len(script):
        i1, j1 = i, j
        if script[k].kind == KEEP:
            while k < len(script) and script[k].kind == KEEP:
                i, j, k = i + 1, j + 1, k + 1
            codes.append(("equal", i1, i, j1, j))
        else:
            while k < len(script) and script[k].kind != KEEP:
                if script[k].kind == DELETE:
                    i += 1
                else:
                    j += 1
                k += 1
            tag = "replace" if i > i1 and j > j1 else ("delete" if i > i1 else "insert")
            codes.append((tag, i1, i, j1, j))
    return codes


def _range(start: int, stop: int) -> str:
    length = stop - start
    first = start + 1
    if length == 1:
        return f"{first}"
    if length == 0:
        first -= 1
    return f"{first},{length}"


def unified_diff(a: Sequence[str], b: Sequence[str], script: Sequence[Op], context: int = 3,
                 from_name: str = "a", to_name: str = "b") -> list[str]:
    """Return the lines of a unified diff of the script, without line feeds, in the layout of GNU diff -u.

    The hunks are grouped as difflib.unified_diff groups them, so for the same
    matching the output is the same. If the script changes nothing, the result is [].
    """
    codes = _opcodes(script)
    if not codes:
        codes = [("equal", 0, 1, 0, 1)]
    n = context
    if codes[0][0] == "equal":
        tag, i1, i2, j1, j2 = codes[0]
        codes[0] = (tag, max(i1, i2 - n), i2, max(j1, j2 - n), j2)
    if codes[-1][0] == "equal":
        tag, i1, i2, j1, j2 = codes[-1]
        codes[-1] = (tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n))
    groups: list[list[tuple[str, int, int, int, int]]] = []
    group: list[tuple[str, int, int, int, int]] = []
    for tag, i1, i2, j1, j2 in codes:
        if tag == "equal" and i2 - i1 > 2 * n:
            group.append((tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)))
            groups.append(group)
            group = []
            i1, j1 = max(i1, i2 - n), max(j1, j2 - n)
        group.append((tag, i1, i2, j1, j2))
    if group and not (len(group) == 1 and group[0][0] == "equal"):
        groups.append(group)
    out: list[str] = []
    for group in groups:
        if not out:
            out += [f"--- {from_name}", f"+++ {to_name}"]
        first, last = group[0], group[-1]
        out.append(f"@@ -{_range(first[1], last[2])} +{_range(first[3], last[4])} @@")
        for tag, i1, i2, j1, j2 in group:
            if tag == "equal":
                out += [" " + line for line in a[i1:i2]]
                continue
            if tag in ("replace", "delete"):
                out += ["-" + line for line in a[i1:i2]]
            if tag in ("replace", "insert"):
                out += ["+" + line for line in b[j1:j2]]
    return out
test_patience_diff.py 80 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/patience-diff/. The authors are listed in prov/3MB06K.jsonl.

import random
from collections import Counter

from patience_diff import longest_increasing, patience_diff, patience_matching, unique_common
from txdiff import is_matching, is_valid_script, lcs_matching, matching_to_script, script_cost, unified_diff

OLD = ["void func1() {", "    x += 1", "}", "", "void func2() {", "    x += 2", "}"]
NEW = ["void func1() {", "    x += 1", "}", "", "void functhreehalves() {", "    x += 1.5", "}", "",
       "void func2() {", "    x += 2", "}"]


def test_inserted_function() -> None:
    pairs = patience_matching(OLD, NEW)
    assert pairs == [(0, 0), (1, 1), (2, 2), (3, 3), (4, 8), (5, 9), (6, 10)]
    diff = unified_diff(OLD, NEW, matching_to_script(OLD, NEW, pairs))
    assert diff[6:10] == ["+void functhreehalves() {", "+    x += 1.5", "+}", "+"]
    # A shifted matching of the same length keeps the closing brace and blank line of func1
    # with those of the new function. It is just as short, so a minimum diff may print it.
    shifted = [(0, 0), (1, 1), (2, 6), (3, 7), (4, 8), (5, 9), (6, 10)]
    assert is_matching(OLD, NEW, shifted) and len(shifted) == len(lcs_matching(OLD, NEW))


def test_check_value() -> None:
    a, b = list("uaaav"), list("aaauv")
    for fallback in (None, "lcs"):
        assert patience_matching(a, b, fallback) == [(0, 3), (4, 4)]
        assert script_cost(patience_diff(a, b, fallback)) == 6
    assert len(a) + len(b) - 2 * len(lcs_matching(a, b)) == 2


def test_counts_are_taken_again_in_each_gap() -> None:
    # Only U is unique in the whole files, but a and b are unique inside each gap.
    a, b = list("abUba"), list("baUab")
    assert unique_common(a, b, 0, 5, 0, 5) == [(2, 2)]
    assert patience_matching(a, b) == [(1, 0), (2, 2), (4, 3)]


def test_fallback() -> None:
    a, b = list("abab"), list("baba")
    assert patience_matching(a, b) == []
    assert patience_matching(a, b, "lcs") == [(1, 0), (2, 1), (3, 2)]


def test_longest_increasing() -> None:
    assert longest_increasing([]) == []
    assert longest_increasing([(0, 3), (1, 1), (2, 2), (3, 0), (4, 4)]) == [(1, 1), (2, 2), (4, 4)]


def test_unique_lines_give_a_longest_matching() -> None:
    rng = random.Random(3)
    for n in range(0, 12):
        for _ in range(20):
            a = list(range(n))
            b = [x for x in a if rng.random() < 0.8] + [100 + t for t in range(rng.randint(0, 3))]
            rng.shuffle(b)
            pairs = patience_matching(a, b)
            assert len(pairs) == len(lcs_matching(a, b))


def test_random_properties() -> None:
    rng = random.Random(9)
    for _ in range(500):
        alpha = "abcdefg"[: rng.randint(1, 7)]
        a = [rng.choice(alpha) for _ in range(rng.randint(0, 10))]
        b = [rng.choice(alpha) for _ in range(rng.randint(0, 10))]
        best = len(lcs_matching(a, b))
        plain = patience_matching(a, b)
        full = patience_matching(a, b, "lcs")
        for pairs in (plain, full):
            assert is_matching(a, b, pairs)
            assert len(pairs) <= best
            assert is_valid_script(a, b, matching_to_script(a, b, pairs))
        # The fallback only adds pairs in ranges that have no unique common line.
        assert set(plain) <= set(full)
        ca, cb = Counter(a), Counter(b)
        if a and b and all(ca[x] == 1 for x in a) and all(cb[x] == 1 for x in b):
            assert len(plain) == best

History

Bram Cohen designed patience diff and described its steps in a blog post in 2010, "Patience Diff Advantages", with the example of a function inserted between two others. The name comes from patience sorting, the card game method that gives a longest increasing subsequence and that Aldous and Diaconis survey. Git provides the method as a diff option and falls back to its ordinary diff in ranges without unique lines. Histogram diff, written for JGit, extends it.

References

  1. Bram Cohen, Patience Diff Advantages, blog post, March 30, 2010, the four steps of the method (equal first lines, equal last lines, the longest common subsequence of the lines that occur once on both sides, and the same steps on each section between matched lines), and the example of a function inserted between two others
  2. Git, the patience diff of the xdiff library (the option --patience), the fallback to the classic diff in a range that has no line that is unique on both sides
  3. David Aldous and Persi Diaconis, Longest increasing subsequences, from patience sorting to the Baik-Deift-Johansson theorem, Bulletin of the AMS 36(4), 1999, 413-432, patience sorting, and the number of piles as the length of a longest increasing subsequence

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example