Append the edits that turn a(a0:a1) into b(b0:b1) along a longest common subsequence
(Hirschberg's algorithm).
| Type | Intent | Optional | Attributes | Name | ||
|---|---|---|---|---|---|---|
| integer, | intent(in) | :: | a(:) |
line numbers of the two texts, from |
||
| integer, | intent(in) | :: | a0 |
the ranges of |
||
| integer, | intent(in) | :: | a1 |
the ranges of |
||
| integer, | intent(in) | :: | b(:) |
line numbers of the two texts, from |
||
| integer, | intent(in) | :: | b0 |
the ranges of |
||
| integer, | intent(in) | :: | b1 |
the ranges of |
||
| type(edit_t), | intent(inout) | :: | e |
the edits so far; |
recursive subroutine lcs(a, a0, a1, b, b0, b1, e) !! Append the edits that turn `a(a0:a1)` into `b(b0:b1)` along a longest common subsequence !! (Hirschberg's algorithm). integer, intent(in) :: a(:), b(:) !! line numbers of the two texts, from `line_ids` integer, intent(in) :: a0, a1, b0, b1 !! the ranges of `a` and `b` to compare type(edit_t), intent(inout) :: e !! the edits so far; `e%op` must have room for the new ones integer :: lo_a, lo_b, hi_a, hi_b, nsuffix, k ! common prefix and suffix, without recursion lo_a = a0 lo_b = b0 do while (lo_a <= a1 .and. lo_b <= b1) if (a(lo_a) /= b(lo_b)) exit call push(OP_EQUAL) lo_a = lo_a + 1 lo_b = lo_b + 1 end do hi_a = a1 hi_b = b1 nsuffix = 0 do while (hi_a >= lo_a .and. hi_b >= lo_b) if (a(hi_a) /= b(hi_b)) exit hi_a = hi_a - 1 hi_b = hi_b - 1 nsuffix = nsuffix + 1 end do call middle(lo_a, hi_a, lo_b, hi_b) do k = 1, nsuffix call push(OP_EQUAL) end do contains recursive subroutine middle(a0, a1, b0, b1) !! The edits for `a(a0:a1)` and `b(b0:b1)`, which differ at both ends. integer, intent(in) :: a0, a1, b0, b1 !! the ranges of `a` and `b` integer :: fwd(0:b1 - b0 + 1), bwd(0:b1 - b0 + 1) ! (not allocatable: assignment would make them 1-based) integer :: mid, k, best, split, j if (a0 > a1) then do j = b0, b1 call push(OP_INSERT) end do return end if if (b0 > b1) then do j = a0, a1 call push(OP_DELETE) end do return end if if (a0 == a1) then ! one line of a: keep it if it occurs in b do j = b0, b1 if (b(j) == a(a0)) then do k = b0, j - 1 call push(OP_INSERT) end do call push(OP_EQUAL) do k = j + 1, b1 call push(OP_INSERT) end do return end if end do call push(OP_DELETE) do k = b0, b1 call push(OP_INSERT) end do return end if mid = (a0 + a1)/2 fwd = lcs_lengths(a(a0:mid), b(b0:b1)) bwd = lcs_lengths(a(a1:mid + 1:-1), b(b1:b0:-1)) best = -1 split = 0 do k = 0, b1 - b0 + 1 if (fwd(k) + bwd(b1 - b0 + 1 - k) > best) then best = fwd(k) + bwd(b1 - b0 + 1 - k) split = k end if end do call lcs(a, a0, mid, b, b0, b0 + split - 1, e) call lcs(a, mid + 1, a1, b, b0 + split, b1, e) end subroutine middle subroutine push(op) !! Append edit `op` (`OP_EQUAL`, `OP_DELETE` or `OP_INSERT`) to `e`. integer, intent(in) :: op !! the edit e%n = e%n + 1 e%op(e%n) = op end subroutine push end subroutine lcs