diff.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. // Copyright 2017, The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE.md file.
  4. // Package diff implements an algorithm for producing edit-scripts.
  5. // The edit-script is a sequence of operations needed to transform one list
  6. // of symbols into another (or vice-versa). The edits allowed are insertions,
  7. // deletions, and modifications. The summation of all edits is called the
  8. // Levenshtein distance as this problem is well-known in computer science.
  9. //
  10. // This package prioritizes performance over accuracy. That is, the run time
  11. // is more important than obtaining a minimal Levenshtein distance.
  12. package diff
  13. // EditType represents a single operation within an edit-script.
  14. type EditType uint8
  15. const (
  16. // Identity indicates that a symbol pair is identical in both list X and Y.
  17. Identity EditType = iota
  18. // UniqueX indicates that a symbol only exists in X and not Y.
  19. UniqueX
  20. // UniqueY indicates that a symbol only exists in Y and not X.
  21. UniqueY
  22. // Modified indicates that a symbol pair is a modification of each other.
  23. Modified
  24. )
  25. // EditScript represents the series of differences between two lists.
  26. type EditScript []EditType
  27. // String returns a human-readable string representing the edit-script where
  28. // Identity, UniqueX, UniqueY, and Modified are represented by the
  29. // '.', 'X', 'Y', and 'M' characters, respectively.
  30. func (es EditScript) String() string {
  31. b := make([]byte, len(es))
  32. for i, e := range es {
  33. switch e {
  34. case Identity:
  35. b[i] = '.'
  36. case UniqueX:
  37. b[i] = 'X'
  38. case UniqueY:
  39. b[i] = 'Y'
  40. case Modified:
  41. b[i] = 'M'
  42. default:
  43. panic("invalid edit-type")
  44. }
  45. }
  46. return string(b)
  47. }
  48. // stats returns a histogram of the number of each type of edit operation.
  49. func (es EditScript) stats() (s struct{ NI, NX, NY, NM int }) {
  50. for _, e := range es {
  51. switch e {
  52. case Identity:
  53. s.NI++
  54. case UniqueX:
  55. s.NX++
  56. case UniqueY:
  57. s.NY++
  58. case Modified:
  59. s.NM++
  60. default:
  61. panic("invalid edit-type")
  62. }
  63. }
  64. return
  65. }
  66. // Dist is the Levenshtein distance and is guaranteed to be 0 if and only if
  67. // lists X and Y are equal.
  68. func (es EditScript) Dist() int { return len(es) - es.stats().NI }
  69. // LenX is the length of the X list.
  70. func (es EditScript) LenX() int { return len(es) - es.stats().NY }
  71. // LenY is the length of the Y list.
  72. func (es EditScript) LenY() int { return len(es) - es.stats().NX }
  73. // EqualFunc reports whether the symbols at indexes ix and iy are equal.
  74. // When called by Difference, the index is guaranteed to be within nx and ny.
  75. type EqualFunc func(ix int, iy int) Result
  76. // Result is the result of comparison.
  77. // NumSame is the number of sub-elements that are equal.
  78. // NumDiff is the number of sub-elements that are not equal.
  79. type Result struct{ NumSame, NumDiff int }
  80. // BoolResult returns a Result that is either Equal or not Equal.
  81. func BoolResult(b bool) Result {
  82. if b {
  83. return Result{NumSame: 1} // Equal, Similar
  84. } else {
  85. return Result{NumDiff: 2} // Not Equal, not Similar
  86. }
  87. }
  88. // Equal indicates whether the symbols are equal. Two symbols are equal
  89. // if and only if NumDiff == 0. If Equal, then they are also Similar.
  90. func (r Result) Equal() bool { return r.NumDiff == 0 }
  91. // Similar indicates whether two symbols are similar and may be represented
  92. // by using the Modified type. As a special case, we consider binary comparisons
  93. // (i.e., those that return Result{1, 0} or Result{0, 1}) to be similar.
  94. //
  95. // The exact ratio of NumSame to NumDiff to determine similarity may change.
  96. func (r Result) Similar() bool {
  97. // Use NumSame+1 to offset NumSame so that binary comparisons are similar.
  98. return r.NumSame+1 >= r.NumDiff
  99. }
  100. // Difference reports whether two lists of lengths nx and ny are equal
  101. // given the definition of equality provided as f.
  102. //
  103. // This function returns an edit-script, which is a sequence of operations
  104. // needed to convert one list into the other. The following invariants for
  105. // the edit-script are maintained:
  106. // • eq == (es.Dist()==0)
  107. // • nx == es.LenX()
  108. // • ny == es.LenY()
  109. //
  110. // This algorithm is not guaranteed to be an optimal solution (i.e., one that
  111. // produces an edit-script with a minimal Levenshtein distance). This algorithm
  112. // favors performance over optimality. The exact output is not guaranteed to
  113. // be stable and may change over time.
  114. func Difference(nx, ny int, f EqualFunc) (es EditScript) {
  115. // This algorithm is based on traversing what is known as an "edit-graph".
  116. // See Figure 1 from "An O(ND) Difference Algorithm and Its Variations"
  117. // by Eugene W. Myers. Since D can be as large as N itself, this is
  118. // effectively O(N^2). Unlike the algorithm from that paper, we are not
  119. // interested in the optimal path, but at least some "decent" path.
  120. //
  121. // For example, let X and Y be lists of symbols:
  122. // X = [A B C A B B A]
  123. // Y = [C B A B A C]
  124. //
  125. // The edit-graph can be drawn as the following:
  126. // A B C A B B A
  127. // ┌─────────────┐
  128. // C │_|_|\|_|_|_|_│ 0
  129. // B │_|\|_|_|\|\|_│ 1
  130. // A │\|_|_|\|_|_|\│ 2
  131. // B │_|\|_|_|\|\|_│ 3
  132. // A │\|_|_|\|_|_|\│ 4
  133. // C │ | |\| | | | │ 5
  134. // └─────────────┘ 6
  135. // 0 1 2 3 4 5 6 7
  136. //
  137. // List X is written along the horizontal axis, while list Y is written
  138. // along the vertical axis. At any point on this grid, if the symbol in
  139. // list X matches the corresponding symbol in list Y, then a '\' is drawn.
  140. // The goal of any minimal edit-script algorithm is to find a path from the
  141. // top-left corner to the bottom-right corner, while traveling through the
  142. // fewest horizontal or vertical edges.
  143. // A horizontal edge is equivalent to inserting a symbol from list X.
  144. // A vertical edge is equivalent to inserting a symbol from list Y.
  145. // A diagonal edge is equivalent to a matching symbol between both X and Y.
  146. // Invariants:
  147. // • 0 ≤ fwdPath.X ≤ (fwdFrontier.X, revFrontier.X) ≤ revPath.X ≤ nx
  148. // • 0 ≤ fwdPath.Y ≤ (fwdFrontier.Y, revFrontier.Y) ≤ revPath.Y ≤ ny
  149. //
  150. // In general:
  151. // • fwdFrontier.X < revFrontier.X
  152. // • fwdFrontier.Y < revFrontier.Y
  153. // Unless, it is time for the algorithm to terminate.
  154. fwdPath := path{+1, point{0, 0}, make(EditScript, 0, (nx+ny)/2)}
  155. revPath := path{-1, point{nx, ny}, make(EditScript, 0)}
  156. fwdFrontier := fwdPath.point // Forward search frontier
  157. revFrontier := revPath.point // Reverse search frontier
  158. // Search budget bounds the cost of searching for better paths.
  159. // The longest sequence of non-matching symbols that can be tolerated is
  160. // approximately the square-root of the search budget.
  161. searchBudget := 4 * (nx + ny) // O(n)
  162. // The algorithm below is a greedy, meet-in-the-middle algorithm for
  163. // computing sub-optimal edit-scripts between two lists.
  164. //
  165. // The algorithm is approximately as follows:
  166. // • Searching for differences switches back-and-forth between
  167. // a search that starts at the beginning (the top-left corner), and
  168. // a search that starts at the end (the bottom-right corner). The goal of
  169. // the search is connect with the search from the opposite corner.
  170. // • As we search, we build a path in a greedy manner, where the first
  171. // match seen is added to the path (this is sub-optimal, but provides a
  172. // decent result in practice). When matches are found, we try the next pair
  173. // of symbols in the lists and follow all matches as far as possible.
  174. // • When searching for matches, we search along a diagonal going through
  175. // through the "frontier" point. If no matches are found, we advance the
  176. // frontier towards the opposite corner.
  177. // • This algorithm terminates when either the X coordinates or the
  178. // Y coordinates of the forward and reverse frontier points ever intersect.
  179. //
  180. // This algorithm is correct even if searching only in the forward direction
  181. // or in the reverse direction. We do both because it is commonly observed
  182. // that two lists commonly differ because elements were added to the front
  183. // or end of the other list.
  184. //
  185. // Running the tests with the "cmp_debug" build tag prints a visualization
  186. // of the algorithm running in real-time. This is educational for
  187. // understanding how the algorithm works. See debug_enable.go.
  188. f = debug.Begin(nx, ny, f, &fwdPath.es, &revPath.es)
  189. for {
  190. // Forward search from the beginning.
  191. if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 {
  192. break
  193. }
  194. for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ {
  195. // Search in a diagonal pattern for a match.
  196. z := zigzag(i)
  197. p := point{fwdFrontier.X + z, fwdFrontier.Y - z}
  198. switch {
  199. case p.X >= revPath.X || p.Y < fwdPath.Y:
  200. stop1 = true // Hit top-right corner
  201. case p.Y >= revPath.Y || p.X < fwdPath.X:
  202. stop2 = true // Hit bottom-left corner
  203. case f(p.X, p.Y).Equal():
  204. // Match found, so connect the path to this point.
  205. fwdPath.connect(p, f)
  206. fwdPath.append(Identity)
  207. // Follow sequence of matches as far as possible.
  208. for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y {
  209. if !f(fwdPath.X, fwdPath.Y).Equal() {
  210. break
  211. }
  212. fwdPath.append(Identity)
  213. }
  214. fwdFrontier = fwdPath.point
  215. stop1, stop2 = true, true
  216. default:
  217. searchBudget-- // Match not found
  218. }
  219. debug.Update()
  220. }
  221. // Advance the frontier towards reverse point.
  222. if revPath.X-fwdFrontier.X >= revPath.Y-fwdFrontier.Y {
  223. fwdFrontier.X++
  224. } else {
  225. fwdFrontier.Y++
  226. }
  227. // Reverse search from the end.
  228. if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 {
  229. break
  230. }
  231. for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ {
  232. // Search in a diagonal pattern for a match.
  233. z := zigzag(i)
  234. p := point{revFrontier.X - z, revFrontier.Y + z}
  235. switch {
  236. case fwdPath.X >= p.X || revPath.Y < p.Y:
  237. stop1 = true // Hit bottom-left corner
  238. case fwdPath.Y >= p.Y || revPath.X < p.X:
  239. stop2 = true // Hit top-right corner
  240. case f(p.X-1, p.Y-1).Equal():
  241. // Match found, so connect the path to this point.
  242. revPath.connect(p, f)
  243. revPath.append(Identity)
  244. // Follow sequence of matches as far as possible.
  245. for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y {
  246. if !f(revPath.X-1, revPath.Y-1).Equal() {
  247. break
  248. }
  249. revPath.append(Identity)
  250. }
  251. revFrontier = revPath.point
  252. stop1, stop2 = true, true
  253. default:
  254. searchBudget-- // Match not found
  255. }
  256. debug.Update()
  257. }
  258. // Advance the frontier towards forward point.
  259. if revFrontier.X-fwdPath.X >= revFrontier.Y-fwdPath.Y {
  260. revFrontier.X--
  261. } else {
  262. revFrontier.Y--
  263. }
  264. }
  265. // Join the forward and reverse paths and then append the reverse path.
  266. fwdPath.connect(revPath.point, f)
  267. for i := len(revPath.es) - 1; i >= 0; i-- {
  268. t := revPath.es[i]
  269. revPath.es = revPath.es[:i]
  270. fwdPath.append(t)
  271. }
  272. debug.Finish()
  273. return fwdPath.es
  274. }
  275. type path struct {
  276. dir int // +1 if forward, -1 if reverse
  277. point // Leading point of the EditScript path
  278. es EditScript
  279. }
  280. // connect appends any necessary Identity, Modified, UniqueX, or UniqueY types
  281. // to the edit-script to connect p.point to dst.
  282. func (p *path) connect(dst point, f EqualFunc) {
  283. if p.dir > 0 {
  284. // Connect in forward direction.
  285. for dst.X > p.X && dst.Y > p.Y {
  286. switch r := f(p.X, p.Y); {
  287. case r.Equal():
  288. p.append(Identity)
  289. case r.Similar():
  290. p.append(Modified)
  291. case dst.X-p.X >= dst.Y-p.Y:
  292. p.append(UniqueX)
  293. default:
  294. p.append(UniqueY)
  295. }
  296. }
  297. for dst.X > p.X {
  298. p.append(UniqueX)
  299. }
  300. for dst.Y > p.Y {
  301. p.append(UniqueY)
  302. }
  303. } else {
  304. // Connect in reverse direction.
  305. for p.X > dst.X && p.Y > dst.Y {
  306. switch r := f(p.X-1, p.Y-1); {
  307. case r.Equal():
  308. p.append(Identity)
  309. case r.Similar():
  310. p.append(Modified)
  311. case p.Y-dst.Y >= p.X-dst.X:
  312. p.append(UniqueY)
  313. default:
  314. p.append(UniqueX)
  315. }
  316. }
  317. for p.X > dst.X {
  318. p.append(UniqueX)
  319. }
  320. for p.Y > dst.Y {
  321. p.append(UniqueY)
  322. }
  323. }
  324. }
  325. func (p *path) append(t EditType) {
  326. p.es = append(p.es, t)
  327. switch t {
  328. case Identity, Modified:
  329. p.add(p.dir, p.dir)
  330. case UniqueX:
  331. p.add(p.dir, 0)
  332. case UniqueY:
  333. p.add(0, p.dir)
  334. }
  335. debug.Update()
  336. }
  337. type point struct{ X, Y int }
  338. func (p *point) add(dx, dy int) { p.X += dx; p.Y += dy }
  339. // zigzag maps a consecutive sequence of integers to a zig-zag sequence.
  340. // [0 1 2 3 4 5 ...] => [0 -1 +1 -2 +2 ...]
  341. func zigzag(x int) int {
  342. if x&1 != 0 {
  343. x = ^x
  344. }
  345. return x >> 1
  346. }