You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1091 lines
23 KiB

  1. // Copyright 2014 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 file.
  4. // Package intsets provides Sparse, a compact and fast representation
  5. // for sparse sets of int values.
  6. //
  7. // The time complexity of the operations Len, Insert, Remove and Has
  8. // is in O(n) but in practice those methods are faster and more
  9. // space-efficient than equivalent operations on sets based on the Go
  10. // map type. The IsEmpty, Min, Max, Clear and TakeMin operations
  11. // require constant time.
  12. //
  13. package intsets // import "golang.org/x/tools/container/intsets"
  14. // TODO(adonovan):
  15. // - Add InsertAll(...int), RemoveAll(...int)
  16. // - Add 'bool changed' results for {Intersection,Difference}With too.
  17. //
  18. // TODO(adonovan): implement Dense, a dense bit vector with a similar API.
  19. // The space usage would be proportional to Max(), not Len(), and the
  20. // implementation would be based upon big.Int.
  21. //
  22. // TODO(adonovan): opt: make UnionWith and Difference faster.
  23. // These are the hot-spots for go/pointer.
  24. import (
  25. "bytes"
  26. "fmt"
  27. )
  28. // A Sparse is a set of int values.
  29. // Sparse operations (even queries) are not concurrency-safe.
  30. //
  31. // The zero value for Sparse is a valid empty set.
  32. //
  33. // Sparse sets must be copied using the Copy method, not by assigning
  34. // a Sparse value.
  35. //
  36. type Sparse struct {
  37. // An uninitialized Sparse represents an empty set.
  38. // An empty set may also be represented by
  39. // root.next == root.prev == &root.
  40. //
  41. // The root is always the block with the smallest offset.
  42. // It can be empty, but only if it is the only block; in that case, offset is
  43. // MaxInt (which is not a valid offset).
  44. root block
  45. }
  46. type word uintptr
  47. const (
  48. _m = ^word(0)
  49. bitsPerWord = 8 << (_m>>8&1 + _m>>16&1 + _m>>32&1)
  50. bitsPerBlock = 256 // optimal value for go/pointer solver performance
  51. wordsPerBlock = bitsPerBlock / bitsPerWord
  52. )
  53. // Limit values of implementation-specific int type.
  54. const (
  55. MaxInt = int(^uint(0) >> 1)
  56. MinInt = -MaxInt - 1
  57. )
  58. // -- block ------------------------------------------------------------
  59. // A set is represented as a circular doubly-linked list of blocks,
  60. // each containing an offset and a bit array of fixed size
  61. // bitsPerBlock; the blocks are ordered by increasing offset.
  62. //
  63. // The set contains an element x iff the block whose offset is x - (x
  64. // mod bitsPerBlock) has the bit (x mod bitsPerBlock) set, where mod
  65. // is the Euclidean remainder.
  66. //
  67. // A block may only be empty transiently.
  68. //
  69. type block struct {
  70. offset int // offset mod bitsPerBlock == 0
  71. bits [wordsPerBlock]word // contains at least one set bit
  72. next, prev *block // doubly-linked list of blocks
  73. }
  74. // wordMask returns the word index (in block.bits)
  75. // and single-bit mask for the block's ith bit.
  76. func wordMask(i uint) (w uint, mask word) {
  77. w = i / bitsPerWord
  78. mask = 1 << (i % bitsPerWord)
  79. return
  80. }
  81. // insert sets the block b's ith bit and
  82. // returns true if it was not already set.
  83. //
  84. func (b *block) insert(i uint) bool {
  85. w, mask := wordMask(i)
  86. if b.bits[w]&mask == 0 {
  87. b.bits[w] |= mask
  88. return true
  89. }
  90. return false
  91. }
  92. // remove clears the block's ith bit and
  93. // returns true if the bit was previously set.
  94. // NB: may leave the block empty.
  95. //
  96. func (b *block) remove(i uint) bool {
  97. w, mask := wordMask(i)
  98. if b.bits[w]&mask != 0 {
  99. b.bits[w] &^= mask
  100. return true
  101. }
  102. return false
  103. }
  104. // has reports whether the block's ith bit is set.
  105. func (b *block) has(i uint) bool {
  106. w, mask := wordMask(i)
  107. return b.bits[w]&mask != 0
  108. }
  109. // empty reports whether b.len()==0, but more efficiently.
  110. func (b *block) empty() bool {
  111. for _, w := range b.bits {
  112. if w != 0 {
  113. return false
  114. }
  115. }
  116. return true
  117. }
  118. // len returns the number of set bits in block b.
  119. func (b *block) len() int {
  120. var l int
  121. for _, w := range b.bits {
  122. l += popcount(w)
  123. }
  124. return l
  125. }
  126. // max returns the maximum element of the block.
  127. // The block must not be empty.
  128. func (b *block) max() int {
  129. bi := b.offset + bitsPerBlock
  130. // Decrement bi by number of high zeros in last.bits.
  131. for i := len(b.bits) - 1; i >= 0; i-- {
  132. if w := b.bits[i]; w != 0 {
  133. return bi - nlz(w) - 1
  134. }
  135. bi -= bitsPerWord
  136. }
  137. panic("BUG: empty block")
  138. }
  139. // min returns the minimum element of the block,
  140. // and also removes it if take is set.
  141. // The block must not be initially empty.
  142. // NB: may leave the block empty.
  143. func (b *block) min(take bool) int {
  144. for i, w := range b.bits {
  145. if w != 0 {
  146. tz := ntz(w)
  147. if take {
  148. b.bits[i] = w &^ (1 << uint(tz))
  149. }
  150. return b.offset + int(i*bitsPerWord) + tz
  151. }
  152. }
  153. panic("BUG: empty block")
  154. }
  155. // lowerBound returns the smallest element of the block that is greater than or
  156. // equal to the element corresponding to the ith bit. If there is no such
  157. // element, the second return value is false.
  158. func (b *block) lowerBound(i uint) (int, bool) {
  159. w := i / bitsPerWord
  160. bit := i % bitsPerWord
  161. if val := b.bits[w] >> bit; val != 0 {
  162. return b.offset + int(i) + ntz(val), true
  163. }
  164. for w++; w < wordsPerBlock; w++ {
  165. if val := b.bits[w]; val != 0 {
  166. return b.offset + int(w*bitsPerWord) + ntz(val), true
  167. }
  168. }
  169. return 0, false
  170. }
  171. // forEach calls f for each element of block b.
  172. // f must not mutate b's enclosing Sparse.
  173. func (b *block) forEach(f func(int)) {
  174. for i, w := range b.bits {
  175. offset := b.offset + i*bitsPerWord
  176. for bi := 0; w != 0 && bi < bitsPerWord; bi++ {
  177. if w&1 != 0 {
  178. f(offset)
  179. }
  180. offset++
  181. w >>= 1
  182. }
  183. }
  184. }
  185. // offsetAndBitIndex returns the offset of the block that would
  186. // contain x and the bit index of x within that block.
  187. //
  188. func offsetAndBitIndex(x int) (int, uint) {
  189. mod := x % bitsPerBlock
  190. if mod < 0 {
  191. // Euclidean (non-negative) remainder
  192. mod += bitsPerBlock
  193. }
  194. return x - mod, uint(mod)
  195. }
  196. // -- Sparse --------------------------------------------------------------
  197. // none is a shared, empty, sentinel block that indicates the end of a block
  198. // list.
  199. var none block
  200. // Dummy type used to generate an implicit panic. This must be defined at the
  201. // package level; if it is defined inside a function, it prevents the inlining
  202. // of that function.
  203. type to_copy_a_sparse_you_must_call_its_Copy_method struct{}
  204. // init ensures s is properly initialized.
  205. func (s *Sparse) init() {
  206. root := &s.root
  207. if root.next == nil {
  208. root.offset = MaxInt
  209. root.next = root
  210. root.prev = root
  211. } else if root.next.prev != root {
  212. // Copying a Sparse x leads to pernicious corruption: the
  213. // new Sparse y shares the old linked list, but iteration
  214. // on y will never encounter &y.root so it goes into a
  215. // loop. Fail fast before this occurs.
  216. // We don't want to call panic here because it prevents the
  217. // inlining of this function.
  218. _ = (interface{}(nil)).(to_copy_a_sparse_you_must_call_its_Copy_method)
  219. }
  220. }
  221. func (s *Sparse) first() *block {
  222. s.init()
  223. if s.root.offset == MaxInt {
  224. return &none
  225. }
  226. return &s.root
  227. }
  228. // next returns the next block in the list, or end if b is the last block.
  229. func (s *Sparse) next(b *block) *block {
  230. if b.next == &s.root {
  231. return &none
  232. }
  233. return b.next
  234. }
  235. // prev returns the previous block in the list, or end if b is the first block.
  236. func (s *Sparse) prev(b *block) *block {
  237. if b.prev == &s.root {
  238. return &none
  239. }
  240. return b.prev
  241. }
  242. // IsEmpty reports whether the set s is empty.
  243. func (s *Sparse) IsEmpty() bool {
  244. return s.root.next == nil || s.root.offset == MaxInt
  245. }
  246. // Len returns the number of elements in the set s.
  247. func (s *Sparse) Len() int {
  248. var l int
  249. for b := s.first(); b != &none; b = s.next(b) {
  250. l += b.len()
  251. }
  252. return l
  253. }
  254. // Max returns the maximum element of the set s, or MinInt if s is empty.
  255. func (s *Sparse) Max() int {
  256. if s.IsEmpty() {
  257. return MinInt
  258. }
  259. return s.root.prev.max()
  260. }
  261. // Min returns the minimum element of the set s, or MaxInt if s is empty.
  262. func (s *Sparse) Min() int {
  263. if s.IsEmpty() {
  264. return MaxInt
  265. }
  266. return s.root.min(false)
  267. }
  268. // LowerBound returns the smallest element >= x, or MaxInt if there is no such
  269. // element.
  270. func (s *Sparse) LowerBound(x int) int {
  271. offset, i := offsetAndBitIndex(x)
  272. for b := s.first(); b != &none; b = s.next(b) {
  273. if b.offset > offset {
  274. return b.min(false)
  275. }
  276. if b.offset == offset {
  277. if y, ok := b.lowerBound(i); ok {
  278. return y
  279. }
  280. }
  281. }
  282. return MaxInt
  283. }
  284. // block returns the block that would contain offset,
  285. // or nil if s contains no such block.
  286. // Precondition: offset is a multiple of bitsPerBlock.
  287. func (s *Sparse) block(offset int) *block {
  288. for b := s.first(); b != &none && b.offset <= offset; b = s.next(b) {
  289. if b.offset == offset {
  290. return b
  291. }
  292. }
  293. return nil
  294. }
  295. // Insert adds x to the set s, and reports whether the set grew.
  296. func (s *Sparse) Insert(x int) bool {
  297. offset, i := offsetAndBitIndex(x)
  298. b := s.first()
  299. for ; b != &none && b.offset <= offset; b = s.next(b) {
  300. if b.offset == offset {
  301. return b.insert(i)
  302. }
  303. }
  304. // Insert new block before b.
  305. new := s.insertBlockBefore(b)
  306. new.offset = offset
  307. return new.insert(i)
  308. }
  309. // removeBlock removes a block and returns the block that followed it (or end if
  310. // it was the last block).
  311. func (s *Sparse) removeBlock(b *block) *block {
  312. if b != &s.root {
  313. b.prev.next = b.next
  314. b.next.prev = b.prev
  315. if b.next == &s.root {
  316. return &none
  317. }
  318. return b.next
  319. }
  320. first := s.root.next
  321. if first == &s.root {
  322. // This was the only block.
  323. s.Clear()
  324. return &none
  325. }
  326. s.root.offset = first.offset
  327. s.root.bits = first.bits
  328. if first.next == &s.root {
  329. // Single block remaining.
  330. s.root.next = &s.root
  331. s.root.prev = &s.root
  332. } else {
  333. s.root.next = first.next
  334. first.next.prev = &s.root
  335. }
  336. return &s.root
  337. }
  338. // Remove removes x from the set s, and reports whether the set shrank.
  339. func (s *Sparse) Remove(x int) bool {
  340. offset, i := offsetAndBitIndex(x)
  341. if b := s.block(offset); b != nil {
  342. if !b.remove(i) {
  343. return false
  344. }
  345. if b.empty() {
  346. s.removeBlock(b)
  347. }
  348. return true
  349. }
  350. return false
  351. }
  352. // Clear removes all elements from the set s.
  353. func (s *Sparse) Clear() {
  354. s.root = block{
  355. offset: MaxInt,
  356. next: &s.root,
  357. prev: &s.root,
  358. }
  359. }
  360. // If set s is non-empty, TakeMin sets *p to the minimum element of
  361. // the set s, removes that element from the set and returns true.
  362. // Otherwise, it returns false and *p is undefined.
  363. //
  364. // This method may be used for iteration over a worklist like so:
  365. //
  366. // var x int
  367. // for worklist.TakeMin(&x) { use(x) }
  368. //
  369. func (s *Sparse) TakeMin(p *int) bool {
  370. if s.IsEmpty() {
  371. return false
  372. }
  373. *p = s.root.min(true)
  374. if s.root.empty() {
  375. s.removeBlock(&s.root)
  376. }
  377. return true
  378. }
  379. // Has reports whether x is an element of the set s.
  380. func (s *Sparse) Has(x int) bool {
  381. offset, i := offsetAndBitIndex(x)
  382. if b := s.block(offset); b != nil {
  383. return b.has(i)
  384. }
  385. return false
  386. }
  387. // forEach applies function f to each element of the set s in order.
  388. //
  389. // f must not mutate s. Consequently, forEach is not safe to expose
  390. // to clients. In any case, using "range s.AppendTo()" allows more
  391. // natural control flow with continue/break/return.
  392. //
  393. func (s *Sparse) forEach(f func(int)) {
  394. for b := s.first(); b != &none; b = s.next(b) {
  395. b.forEach(f)
  396. }
  397. }
  398. // Copy sets s to the value of x.
  399. func (s *Sparse) Copy(x *Sparse) {
  400. if s == x {
  401. return
  402. }
  403. xb := x.first()
  404. sb := s.first()
  405. for xb != &none {
  406. if sb == &none {
  407. sb = s.insertBlockBefore(sb)
  408. }
  409. sb.offset = xb.offset
  410. sb.bits = xb.bits
  411. xb = x.next(xb)
  412. sb = s.next(sb)
  413. }
  414. s.discardTail(sb)
  415. }
  416. // insertBlockBefore returns a new block, inserting it before next.
  417. // If next is the root, the root is replaced. If next is end, the block is
  418. // inserted at the end.
  419. func (s *Sparse) insertBlockBefore(next *block) *block {
  420. if s.IsEmpty() {
  421. if next != &none {
  422. panic("BUG: passed block with empty set")
  423. }
  424. return &s.root
  425. }
  426. if next == &s.root {
  427. // Special case: we need to create a new block that will become the root
  428. // block.The old root block becomes the second block.
  429. second := s.root
  430. s.root = block{
  431. next: &second,
  432. }
  433. if second.next == &s.root {
  434. s.root.prev = &second
  435. } else {
  436. s.root.prev = second.prev
  437. second.next.prev = &second
  438. second.prev = &s.root
  439. }
  440. return &s.root
  441. }
  442. if next == &none {
  443. // Insert before root.
  444. next = &s.root
  445. }
  446. b := new(block)
  447. b.next = next
  448. b.prev = next.prev
  449. b.prev.next = b
  450. next.prev = b
  451. return b
  452. }
  453. // discardTail removes block b and all its successors from s.
  454. func (s *Sparse) discardTail(b *block) {
  455. if b != &none {
  456. if b == &s.root {
  457. s.Clear()
  458. } else {
  459. b.prev.next = &s.root
  460. s.root.prev = b.prev
  461. }
  462. }
  463. }
  464. // IntersectionWith sets s to the intersection s ∩ x.
  465. func (s *Sparse) IntersectionWith(x *Sparse) {
  466. if s == x {
  467. return
  468. }
  469. xb := x.first()
  470. sb := s.first()
  471. for xb != &none && sb != &none {
  472. switch {
  473. case xb.offset < sb.offset:
  474. xb = x.next(xb)
  475. case xb.offset > sb.offset:
  476. sb = s.removeBlock(sb)
  477. default:
  478. var sum word
  479. for i := range sb.bits {
  480. r := xb.bits[i] & sb.bits[i]
  481. sb.bits[i] = r
  482. sum |= r
  483. }
  484. if sum != 0 {
  485. sb = s.next(sb)
  486. } else {
  487. // sb will be overwritten or removed
  488. }
  489. xb = x.next(xb)
  490. }
  491. }
  492. s.discardTail(sb)
  493. }
  494. // Intersection sets s to the intersection x ∩ y.
  495. func (s *Sparse) Intersection(x, y *Sparse) {
  496. switch {
  497. case s == x:
  498. s.IntersectionWith(y)
  499. return
  500. case s == y:
  501. s.IntersectionWith(x)
  502. return
  503. case x == y:
  504. s.Copy(x)
  505. return
  506. }
  507. xb := x.first()
  508. yb := y.first()
  509. sb := s.first()
  510. for xb != &none && yb != &none {
  511. switch {
  512. case xb.offset < yb.offset:
  513. xb = x.next(xb)
  514. continue
  515. case xb.offset > yb.offset:
  516. yb = y.next(yb)
  517. continue
  518. }
  519. if sb == &none {
  520. sb = s.insertBlockBefore(sb)
  521. }
  522. sb.offset = xb.offset
  523. var sum word
  524. for i := range sb.bits {
  525. r := xb.bits[i] & yb.bits[i]
  526. sb.bits[i] = r
  527. sum |= r
  528. }
  529. if sum != 0 {
  530. sb = s.next(sb)
  531. } else {
  532. // sb will be overwritten or removed
  533. }
  534. xb = x.next(xb)
  535. yb = y.next(yb)
  536. }
  537. s.discardTail(sb)
  538. }
  539. // Intersects reports whether s ∩ x ≠ ∅.
  540. func (s *Sparse) Intersects(x *Sparse) bool {
  541. sb := s.first()
  542. xb := x.first()
  543. for sb != &none && xb != &none {
  544. switch {
  545. case xb.offset < sb.offset:
  546. xb = x.next(xb)
  547. case xb.offset > sb.offset:
  548. sb = s.next(sb)
  549. default:
  550. for i := range sb.bits {
  551. if sb.bits[i]&xb.bits[i] != 0 {
  552. return true
  553. }
  554. }
  555. sb = s.next(sb)
  556. xb = x.next(xb)
  557. }
  558. }
  559. return false
  560. }
  561. // UnionWith sets s to the union s ∪ x, and reports whether s grew.
  562. func (s *Sparse) UnionWith(x *Sparse) bool {
  563. if s == x {
  564. return false
  565. }
  566. var changed bool
  567. xb := x.first()
  568. sb := s.first()
  569. for xb != &none {
  570. if sb != &none && sb.offset == xb.offset {
  571. for i := range xb.bits {
  572. if sb.bits[i] != xb.bits[i] {
  573. sb.bits[i] |= xb.bits[i]
  574. changed = true
  575. }
  576. }
  577. xb = x.next(xb)
  578. } else if sb == &none || sb.offset > xb.offset {
  579. sb = s.insertBlockBefore(sb)
  580. sb.offset = xb.offset
  581. sb.bits = xb.bits
  582. changed = true
  583. xb = x.next(xb)
  584. }
  585. sb = s.next(sb)
  586. }
  587. return changed
  588. }
  589. // Union sets s to the union x ∪ y.
  590. func (s *Sparse) Union(x, y *Sparse) {
  591. switch {
  592. case x == y:
  593. s.Copy(x)
  594. return
  595. case s == x:
  596. s.UnionWith(y)
  597. return
  598. case s == y:
  599. s.UnionWith(x)
  600. return
  601. }
  602. xb := x.first()
  603. yb := y.first()
  604. sb := s.first()
  605. for xb != &none || yb != &none {
  606. if sb == &none {
  607. sb = s.insertBlockBefore(sb)
  608. }
  609. switch {
  610. case yb == &none || (xb != &none && xb.offset < yb.offset):
  611. sb.offset = xb.offset
  612. sb.bits = xb.bits
  613. xb = x.next(xb)
  614. case xb == &none || (yb != &none && yb.offset < xb.offset):
  615. sb.offset = yb.offset
  616. sb.bits = yb.bits
  617. yb = y.next(yb)
  618. default:
  619. sb.offset = xb.offset
  620. for i := range xb.bits {
  621. sb.bits[i] = xb.bits[i] | yb.bits[i]
  622. }
  623. xb = x.next(xb)
  624. yb = y.next(yb)
  625. }
  626. sb = s.next(sb)
  627. }
  628. s.discardTail(sb)
  629. }
  630. // DifferenceWith sets s to the difference s ∖ x.
  631. func (s *Sparse) DifferenceWith(x *Sparse) {
  632. if s == x {
  633. s.Clear()
  634. return
  635. }
  636. xb := x.first()
  637. sb := s.first()
  638. for xb != &none && sb != &none {
  639. switch {
  640. case xb.offset > sb.offset:
  641. sb = s.next(sb)
  642. case xb.offset < sb.offset:
  643. xb = x.next(xb)
  644. default:
  645. var sum word
  646. for i := range sb.bits {
  647. r := sb.bits[i] & ^xb.bits[i]
  648. sb.bits[i] = r
  649. sum |= r
  650. }
  651. if sum == 0 {
  652. sb = s.removeBlock(sb)
  653. } else {
  654. sb = s.next(sb)
  655. }
  656. xb = x.next(xb)
  657. }
  658. }
  659. }
  660. // Difference sets s to the difference x ∖ y.
  661. func (s *Sparse) Difference(x, y *Sparse) {
  662. switch {
  663. case x == y:
  664. s.Clear()
  665. return
  666. case s == x:
  667. s.DifferenceWith(y)
  668. return
  669. case s == y:
  670. var y2 Sparse
  671. y2.Copy(y)
  672. s.Difference(x, &y2)
  673. return
  674. }
  675. xb := x.first()
  676. yb := y.first()
  677. sb := s.first()
  678. for xb != &none && yb != &none {
  679. if xb.offset > yb.offset {
  680. // y has block, x has &none
  681. yb = y.next(yb)
  682. continue
  683. }
  684. if sb == &none {
  685. sb = s.insertBlockBefore(sb)
  686. }
  687. sb.offset = xb.offset
  688. switch {
  689. case xb.offset < yb.offset:
  690. // x has block, y has &none
  691. sb.bits = xb.bits
  692. sb = s.next(sb)
  693. default:
  694. // x and y have corresponding blocks
  695. var sum word
  696. for i := range sb.bits {
  697. r := xb.bits[i] & ^yb.bits[i]
  698. sb.bits[i] = r
  699. sum |= r
  700. }
  701. if sum != 0 {
  702. sb = s.next(sb)
  703. } else {
  704. // sb will be overwritten or removed
  705. }
  706. yb = y.next(yb)
  707. }
  708. xb = x.next(xb)
  709. }
  710. for xb != &none {
  711. if sb == &none {
  712. sb = s.insertBlockBefore(sb)
  713. }
  714. sb.offset = xb.offset
  715. sb.bits = xb.bits
  716. sb = s.next(sb)
  717. xb = x.next(xb)
  718. }
  719. s.discardTail(sb)
  720. }
  721. // SymmetricDifferenceWith sets s to the symmetric difference s ∆ x.
  722. func (s *Sparse) SymmetricDifferenceWith(x *Sparse) {
  723. if s == x {
  724. s.Clear()
  725. return
  726. }
  727. sb := s.first()
  728. xb := x.first()
  729. for xb != &none && sb != &none {
  730. switch {
  731. case sb.offset < xb.offset:
  732. sb = s.next(sb)
  733. case xb.offset < sb.offset:
  734. nb := s.insertBlockBefore(sb)
  735. nb.offset = xb.offset
  736. nb.bits = xb.bits
  737. xb = x.next(xb)
  738. default:
  739. var sum word
  740. for i := range sb.bits {
  741. r := sb.bits[i] ^ xb.bits[i]
  742. sb.bits[i] = r
  743. sum |= r
  744. }
  745. if sum == 0 {
  746. sb = s.removeBlock(sb)
  747. } else {
  748. sb = s.next(sb)
  749. }
  750. xb = x.next(xb)
  751. }
  752. }
  753. for xb != &none { // append the tail of x to s
  754. sb = s.insertBlockBefore(sb)
  755. sb.offset = xb.offset
  756. sb.bits = xb.bits
  757. sb = s.next(sb)
  758. xb = x.next(xb)
  759. }
  760. }
  761. // SymmetricDifference sets s to the symmetric difference x ∆ y.
  762. func (s *Sparse) SymmetricDifference(x, y *Sparse) {
  763. switch {
  764. case x == y:
  765. s.Clear()
  766. return
  767. case s == x:
  768. s.SymmetricDifferenceWith(y)
  769. return
  770. case s == y:
  771. s.SymmetricDifferenceWith(x)
  772. return
  773. }
  774. sb := s.first()
  775. xb := x.first()
  776. yb := y.first()
  777. for xb != &none && yb != &none {
  778. if sb == &none {
  779. sb = s.insertBlockBefore(sb)
  780. }
  781. switch {
  782. case yb.offset < xb.offset:
  783. sb.offset = yb.offset
  784. sb.bits = yb.bits
  785. sb = s.next(sb)
  786. yb = y.next(yb)
  787. case xb.offset < yb.offset:
  788. sb.offset = xb.offset
  789. sb.bits = xb.bits
  790. sb = s.next(sb)
  791. xb = x.next(xb)
  792. default:
  793. var sum word
  794. for i := range sb.bits {
  795. r := xb.bits[i] ^ yb.bits[i]
  796. sb.bits[i] = r
  797. sum |= r
  798. }
  799. if sum != 0 {
  800. sb.offset = xb.offset
  801. sb = s.next(sb)
  802. }
  803. xb = x.next(xb)
  804. yb = y.next(yb)
  805. }
  806. }
  807. for xb != &none { // append the tail of x to s
  808. if sb == &none {
  809. sb = s.insertBlockBefore(sb)
  810. }
  811. sb.offset = xb.offset
  812. sb.bits = xb.bits
  813. sb = s.next(sb)
  814. xb = x.next(xb)
  815. }
  816. for yb != &none { // append the tail of y to s
  817. if sb == &none {
  818. sb = s.insertBlockBefore(sb)
  819. }
  820. sb.offset = yb.offset
  821. sb.bits = yb.bits
  822. sb = s.next(sb)
  823. yb = y.next(yb)
  824. }
  825. s.discardTail(sb)
  826. }
  827. // SubsetOf reports whether s ∖ x = ∅.
  828. func (s *Sparse) SubsetOf(x *Sparse) bool {
  829. if s == x {
  830. return true
  831. }
  832. sb := s.first()
  833. xb := x.first()
  834. for sb != &none {
  835. switch {
  836. case xb == &none || xb.offset > sb.offset:
  837. return false
  838. case xb.offset < sb.offset:
  839. xb = x.next(xb)
  840. default:
  841. for i := range sb.bits {
  842. if sb.bits[i]&^xb.bits[i] != 0 {
  843. return false
  844. }
  845. }
  846. sb = s.next(sb)
  847. xb = x.next(xb)
  848. }
  849. }
  850. return true
  851. }
  852. // Equals reports whether the sets s and t have the same elements.
  853. func (s *Sparse) Equals(t *Sparse) bool {
  854. if s == t {
  855. return true
  856. }
  857. sb := s.first()
  858. tb := t.first()
  859. for {
  860. switch {
  861. case sb == &none && tb == &none:
  862. return true
  863. case sb == &none || tb == &none:
  864. return false
  865. case sb.offset != tb.offset:
  866. return false
  867. case sb.bits != tb.bits:
  868. return false
  869. }
  870. sb = s.next(sb)
  871. tb = t.next(tb)
  872. }
  873. }
  874. // String returns a human-readable description of the set s.
  875. func (s *Sparse) String() string {
  876. var buf bytes.Buffer
  877. buf.WriteByte('{')
  878. s.forEach(func(x int) {
  879. if buf.Len() > 1 {
  880. buf.WriteByte(' ')
  881. }
  882. fmt.Fprintf(&buf, "%d", x)
  883. })
  884. buf.WriteByte('}')
  885. return buf.String()
  886. }
  887. // BitString returns the set as a string of 1s and 0s denoting the sum
  888. // of the i'th powers of 2, for each i in s. A radix point, always
  889. // preceded by a digit, appears if the sum is non-integral.
  890. //
  891. // Examples:
  892. // {}.BitString() = "0"
  893. // {4,5}.BitString() = "110000"
  894. // {-3}.BitString() = "0.001"
  895. // {-3,0,4,5}.BitString() = "110001.001"
  896. //
  897. func (s *Sparse) BitString() string {
  898. if s.IsEmpty() {
  899. return "0"
  900. }
  901. min, max := s.Min(), s.Max()
  902. var nbytes int
  903. if max > 0 {
  904. nbytes = max
  905. }
  906. nbytes++ // zero bit
  907. radix := nbytes
  908. if min < 0 {
  909. nbytes += len(".") - min
  910. }
  911. b := make([]byte, nbytes)
  912. for i := range b {
  913. b[i] = '0'
  914. }
  915. if radix < nbytes {
  916. b[radix] = '.'
  917. }
  918. s.forEach(func(x int) {
  919. if x >= 0 {
  920. x += len(".")
  921. }
  922. b[radix-x] = '1'
  923. })
  924. return string(b)
  925. }
  926. // GoString returns a string showing the internal representation of
  927. // the set s.
  928. //
  929. func (s *Sparse) GoString() string {
  930. var buf bytes.Buffer
  931. for b := s.first(); b != &none; b = s.next(b) {
  932. fmt.Fprintf(&buf, "block %p {offset=%d next=%p prev=%p",
  933. b, b.offset, b.next, b.prev)
  934. for _, w := range b.bits {
  935. fmt.Fprintf(&buf, " 0%016x", w)
  936. }
  937. fmt.Fprintf(&buf, "}\n")
  938. }
  939. return buf.String()
  940. }
  941. // AppendTo returns the result of appending the elements of s to slice
  942. // in order.
  943. func (s *Sparse) AppendTo(slice []int) []int {
  944. s.forEach(func(x int) {
  945. slice = append(slice, x)
  946. })
  947. return slice
  948. }
  949. // -- Testing/debugging ------------------------------------------------
  950. // check returns an error if the representation invariants of s are violated.
  951. func (s *Sparse) check() error {
  952. s.init()
  953. if s.root.empty() {
  954. // An empty set must have only the root block with offset MaxInt.
  955. if s.root.next != &s.root {
  956. return fmt.Errorf("multiple blocks with empty root block")
  957. }
  958. if s.root.offset != MaxInt {
  959. return fmt.Errorf("empty set has offset %d, should be MaxInt", s.root.offset)
  960. }
  961. return nil
  962. }
  963. for b := s.first(); ; b = s.next(b) {
  964. if b.offset%bitsPerBlock != 0 {
  965. return fmt.Errorf("bad offset modulo: %d", b.offset)
  966. }
  967. if b.empty() {
  968. return fmt.Errorf("empty block")
  969. }
  970. if b.prev.next != b {
  971. return fmt.Errorf("bad prev.next link")
  972. }
  973. if b.next.prev != b {
  974. return fmt.Errorf("bad next.prev link")
  975. }
  976. if b.next == &s.root {
  977. break
  978. }
  979. if b.offset >= b.next.offset {
  980. return fmt.Errorf("bad offset order: b.offset=%d, b.next.offset=%d",
  981. b.offset, b.next.offset)
  982. }
  983. }
  984. return nil
  985. }