interval_tree.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Copyright 2016 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package adt
  15. import (
  16. "math"
  17. )
  18. // Comparable is an interface for trichotomic comparisons.
  19. type Comparable interface {
  20. // Compare gives the result of a 3-way comparison
  21. // a.Compare(b) = 1 => a > b
  22. // a.Compare(b) = 0 => a == b
  23. // a.Compare(b) = -1 => a < b
  24. Compare(c Comparable) int
  25. }
  26. type rbcolor bool
  27. const black = true
  28. const red = false
  29. // Interval implements a Comparable interval [begin, end)
  30. // TODO: support different sorts of intervals: (a,b), [a,b], (a, b]
  31. type Interval struct {
  32. Begin Comparable
  33. End Comparable
  34. }
  35. // Compare on an interval gives == if the interval overlaps.
  36. func (ivl *Interval) Compare(c Comparable) int {
  37. ivl2 := c.(*Interval)
  38. ivbCmpBegin := ivl.Begin.Compare(ivl2.Begin)
  39. ivbCmpEnd := ivl.Begin.Compare(ivl2.End)
  40. iveCmpBegin := ivl.End.Compare(ivl2.Begin)
  41. // ivl is left of ivl2
  42. if ivbCmpBegin < 0 && iveCmpBegin <= 0 {
  43. return -1
  44. }
  45. // iv is right of iv2
  46. if ivbCmpEnd >= 0 {
  47. return 1
  48. }
  49. return 0
  50. }
  51. type intervalNode struct {
  52. // iv is the interval-value pair entry.
  53. iv IntervalValue
  54. // max endpoint of all descendent nodes.
  55. max Comparable
  56. // left and right are sorted by low endpoint of key interval
  57. left, right *intervalNode
  58. // parent is the direct ancestor of the node
  59. parent *intervalNode
  60. c rbcolor
  61. }
  62. func (x *intervalNode) color() rbcolor {
  63. if x == nil {
  64. return black
  65. }
  66. return x.c
  67. }
  68. func (n *intervalNode) height() int {
  69. if n == nil {
  70. return 0
  71. }
  72. ld := n.left.height()
  73. rd := n.right.height()
  74. if ld < rd {
  75. return rd + 1
  76. }
  77. return ld + 1
  78. }
  79. func (x *intervalNode) min() *intervalNode {
  80. for x.left != nil {
  81. x = x.left
  82. }
  83. return x
  84. }
  85. // successor is the next in-order node in the tree
  86. func (x *intervalNode) successor() *intervalNode {
  87. if x.right != nil {
  88. return x.right.min()
  89. }
  90. y := x.parent
  91. for y != nil && x == y.right {
  92. x = y
  93. y = y.parent
  94. }
  95. return y
  96. }
  97. // updateMax updates the maximum values for a node and its ancestors
  98. func (x *intervalNode) updateMax() {
  99. for x != nil {
  100. oldmax := x.max
  101. max := x.iv.Ivl.End
  102. if x.left != nil && x.left.max.Compare(max) > 0 {
  103. max = x.left.max
  104. }
  105. if x.right != nil && x.right.max.Compare(max) > 0 {
  106. max = x.right.max
  107. }
  108. if oldmax.Compare(max) == 0 {
  109. break
  110. }
  111. x.max = max
  112. x = x.parent
  113. }
  114. }
  115. type nodeVisitor func(n *intervalNode) bool
  116. // visit will call a node visitor on each node that overlaps the given interval
  117. func (x *intervalNode) visit(iv *Interval, nv nodeVisitor) {
  118. if x == nil {
  119. return
  120. }
  121. v := iv.Compare(&x.iv.Ivl)
  122. switch {
  123. case v < 0:
  124. x.left.visit(iv, nv)
  125. case v > 0:
  126. maxiv := Interval{x.iv.Ivl.Begin, x.max}
  127. if maxiv.Compare(iv) == 0 {
  128. x.left.visit(iv, nv)
  129. x.right.visit(iv, nv)
  130. }
  131. default:
  132. nv(x)
  133. x.left.visit(iv, nv)
  134. x.right.visit(iv, nv)
  135. }
  136. }
  137. type IntervalValue struct {
  138. Ivl Interval
  139. Val interface{}
  140. }
  141. // IntervalTree represents a (mostly) textbook implementation of the
  142. // "Introduction to Algorithms" (Cormen et al, 2nd ed.) chapter 13 red-black tree
  143. // and chapter 14.3 interval tree with search supporting "stabbing queries".
  144. type IntervalTree struct {
  145. root *intervalNode
  146. count int
  147. }
  148. // Delete removes the node with the given interval from the tree, returning
  149. // true if a node is in fact removed.
  150. func (ivt *IntervalTree) Delete(ivl Interval) bool {
  151. z := ivt.find(ivl)
  152. if z == nil {
  153. return false
  154. }
  155. y := z
  156. if z.left != nil && z.right != nil {
  157. y = z.successor()
  158. }
  159. x := y.left
  160. if x == nil {
  161. x = y.right
  162. }
  163. if x != nil {
  164. x.parent = y.parent
  165. }
  166. if y.parent == nil {
  167. ivt.root = x
  168. } else {
  169. if y == y.parent.left {
  170. y.parent.left = x
  171. } else {
  172. y.parent.right = x
  173. }
  174. y.parent.updateMax()
  175. }
  176. if y != z {
  177. z.iv = y.iv
  178. z.updateMax()
  179. }
  180. if y.color() == black && x != nil {
  181. ivt.deleteFixup(x)
  182. }
  183. ivt.count--
  184. return true
  185. }
  186. func (ivt *IntervalTree) deleteFixup(x *intervalNode) {
  187. for x != ivt.root && x.color() == black && x.parent != nil {
  188. if x == x.parent.left {
  189. w := x.parent.right
  190. if w.color() == red {
  191. w.c = black
  192. x.parent.c = red
  193. ivt.rotateLeft(x.parent)
  194. w = x.parent.right
  195. }
  196. if w == nil {
  197. break
  198. }
  199. if w.left.color() == black && w.right.color() == black {
  200. w.c = red
  201. x = x.parent
  202. } else {
  203. if w.right.color() == black {
  204. w.left.c = black
  205. w.c = red
  206. ivt.rotateRight(w)
  207. w = x.parent.right
  208. }
  209. w.c = x.parent.color()
  210. x.parent.c = black
  211. w.right.c = black
  212. ivt.rotateLeft(x.parent)
  213. x = ivt.root
  214. }
  215. } else {
  216. // same as above but with left and right exchanged
  217. w := x.parent.left
  218. if w.color() == red {
  219. w.c = black
  220. x.parent.c = red
  221. ivt.rotateRight(x.parent)
  222. w = x.parent.left
  223. }
  224. if w == nil {
  225. break
  226. }
  227. if w.left.color() == black && w.right.color() == black {
  228. w.c = red
  229. x = x.parent
  230. } else {
  231. if w.left.color() == black {
  232. w.right.c = black
  233. w.c = red
  234. ivt.rotateLeft(w)
  235. w = x.parent.left
  236. }
  237. w.c = x.parent.color()
  238. x.parent.c = black
  239. w.left.c = black
  240. ivt.rotateRight(x.parent)
  241. x = ivt.root
  242. }
  243. }
  244. }
  245. if x != nil {
  246. x.c = black
  247. }
  248. }
  249. // Insert adds a node with the given interval into the tree.
  250. func (ivt *IntervalTree) Insert(ivl Interval, val interface{}) {
  251. var y *intervalNode
  252. z := &intervalNode{iv: IntervalValue{ivl, val}, max: ivl.End, c: red}
  253. x := ivt.root
  254. for x != nil {
  255. y = x
  256. if z.iv.Ivl.Begin.Compare(x.iv.Ivl.Begin) < 0 {
  257. x = x.left
  258. } else {
  259. x = x.right
  260. }
  261. }
  262. z.parent = y
  263. if y == nil {
  264. ivt.root = z
  265. } else {
  266. if z.iv.Ivl.Begin.Compare(y.iv.Ivl.Begin) < 0 {
  267. y.left = z
  268. } else {
  269. y.right = z
  270. }
  271. y.updateMax()
  272. }
  273. z.c = red
  274. ivt.insertFixup(z)
  275. ivt.count++
  276. }
  277. func (ivt *IntervalTree) insertFixup(z *intervalNode) {
  278. for z.parent != nil && z.parent.parent != nil && z.parent.color() == red {
  279. if z.parent == z.parent.parent.left {
  280. y := z.parent.parent.right
  281. if y.color() == red {
  282. y.c = black
  283. z.parent.c = black
  284. z.parent.parent.c = red
  285. z = z.parent.parent
  286. } else {
  287. if z == z.parent.right {
  288. z = z.parent
  289. ivt.rotateLeft(z)
  290. }
  291. z.parent.c = black
  292. z.parent.parent.c = red
  293. ivt.rotateRight(z.parent.parent)
  294. }
  295. } else {
  296. // same as then with left/right exchanged
  297. y := z.parent.parent.left
  298. if y.color() == red {
  299. y.c = black
  300. z.parent.c = black
  301. z.parent.parent.c = red
  302. z = z.parent.parent
  303. } else {
  304. if z == z.parent.left {
  305. z = z.parent
  306. ivt.rotateRight(z)
  307. }
  308. z.parent.c = black
  309. z.parent.parent.c = red
  310. ivt.rotateLeft(z.parent.parent)
  311. }
  312. }
  313. }
  314. ivt.root.c = black
  315. }
  316. // rotateLeft moves x so it is left of its right child
  317. func (ivt *IntervalTree) rotateLeft(x *intervalNode) {
  318. y := x.right
  319. x.right = y.left
  320. if y.left != nil {
  321. y.left.parent = x
  322. }
  323. x.updateMax()
  324. ivt.replaceParent(x, y)
  325. y.left = x
  326. y.updateMax()
  327. }
  328. // rotateLeft moves x so it is right of its left child
  329. func (ivt *IntervalTree) rotateRight(x *intervalNode) {
  330. if x == nil {
  331. return
  332. }
  333. y := x.left
  334. x.left = y.right
  335. if y.right != nil {
  336. y.right.parent = x
  337. }
  338. x.updateMax()
  339. ivt.replaceParent(x, y)
  340. y.right = x
  341. y.updateMax()
  342. }
  343. // replaceParent replaces x's parent with y
  344. func (ivt *IntervalTree) replaceParent(x *intervalNode, y *intervalNode) {
  345. y.parent = x.parent
  346. if x.parent == nil {
  347. ivt.root = y
  348. } else {
  349. if x == x.parent.left {
  350. x.parent.left = y
  351. } else {
  352. x.parent.right = y
  353. }
  354. x.parent.updateMax()
  355. }
  356. x.parent = y
  357. }
  358. // Len gives the number of elements in the tree
  359. func (ivt *IntervalTree) Len() int { return ivt.count }
  360. // Height is the number of levels in the tree; one node has height 1.
  361. func (ivt *IntervalTree) Height() int { return ivt.root.height() }
  362. // MaxHeight is the expected maximum tree height given the number of nodes
  363. func (ivt *IntervalTree) MaxHeight() int {
  364. return int((2 * math.Log2(float64(ivt.Len()+1))) + 0.5)
  365. }
  366. // InternalVisitor is used on tree searchs; return false to stop searching.
  367. type IntervalVisitor func(n *IntervalValue) bool
  368. // Visit calls a visitor function on every tree node intersecting the given interval.
  369. func (ivt *IntervalTree) Visit(ivl Interval, ivv IntervalVisitor) {
  370. ivt.root.visit(&ivl, func(n *intervalNode) bool { return ivv(&n.iv) })
  371. }
  372. // find the exact node for a given interval
  373. func (ivt *IntervalTree) find(ivl Interval) (ret *intervalNode) {
  374. f := func(n *intervalNode) bool {
  375. if n.iv.Ivl != ivl {
  376. return true
  377. }
  378. ret = n
  379. return false
  380. }
  381. ivt.root.visit(&ivl, f)
  382. return ret
  383. }
  384. // Find gets the IntervalValue for the node matching the given interval
  385. func (ivt *IntervalTree) Find(ivl Interval) (ret *IntervalValue) {
  386. n := ivt.find(ivl)
  387. if n == nil {
  388. return nil
  389. }
  390. return &n.iv
  391. }
  392. // Contains returns true if there is some tree node intersecting the given interval.
  393. func (ivt *IntervalTree) Contains(iv Interval) bool {
  394. x := ivt.root
  395. for x != nil && iv.Compare(&x.iv.Ivl) != 0 {
  396. if x.left != nil && x.left.max.Compare(iv.Begin) > 0 {
  397. x = x.left
  398. } else {
  399. x = x.right
  400. }
  401. }
  402. return x != nil
  403. }
  404. // Stab returns a slice with all elements in the tree intersecting the interval.
  405. func (ivt *IntervalTree) Stab(iv Interval) (ivs []*IntervalValue) {
  406. f := func(n *IntervalValue) bool { ivs = append(ivs, n); return true }
  407. ivt.Visit(iv, f)
  408. return ivs
  409. }
  410. type StringComparable string
  411. func (s StringComparable) Compare(c Comparable) int {
  412. sc := c.(StringComparable)
  413. if s < sc {
  414. return -1
  415. }
  416. if s > sc {
  417. return 1
  418. }
  419. return 0
  420. }
  421. func NewStringInterval(begin, end string) Interval {
  422. return Interval{StringComparable(begin), StringComparable(end)}
  423. }
  424. func NewStringPoint(s string) Interval {
  425. return Interval{StringComparable(s), StringComparable(s + "\x00")}
  426. }
  427. // StringAffineComparable treats "" as > all other strings
  428. type StringAffineComparable string
  429. func (s StringAffineComparable) Compare(c Comparable) int {
  430. sc := c.(StringAffineComparable)
  431. if len(s) == 0 {
  432. if len(sc) == 0 {
  433. return 0
  434. }
  435. return 1
  436. }
  437. if len(sc) == 0 {
  438. return -1
  439. }
  440. if s < sc {
  441. return -1
  442. }
  443. if s > sc {
  444. return 1
  445. }
  446. return 0
  447. }
  448. func NewStringAffineInterval(begin, end string) Interval {
  449. return Interval{StringAffineComparable(begin), StringAffineComparable(end)}
  450. }
  451. func NewStringAffinePoint(s string) Interval {
  452. return NewStringAffineInterval(s, s+"\x00")
  453. }
  454. func NewInt64Interval(a int64, b int64) Interval {
  455. return Interval{Int64Comparable(a), Int64Comparable(b)}
  456. }
  457. func NewInt64Point(a int64) Interval {
  458. return Interval{Int64Comparable(a), Int64Comparable(a + 1)}
  459. }
  460. type Int64Comparable int64
  461. func (v Int64Comparable) Compare(c Comparable) int {
  462. vc := c.(Int64Comparable)
  463. cmp := v - vc
  464. if cmp < 0 {
  465. return -1
  466. }
  467. if cmp > 0 {
  468. return 1
  469. }
  470. return 0
  471. }