github.com/biogo/store@v0.0.0-20201120204734-aad293a2328f/interval/do_example_test.go (about)

     1  // Copyright ©2012 The bíogo 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  
     5  package interval_test
     6  
     7  import (
     8  	"fmt"
     9  
    10  	"github.com/biogo/store/interval"
    11  )
    12  
    13  func min(a, b Int) Int {
    14  	if a < b {
    15  		return a
    16  	}
    17  	return b
    18  }
    19  
    20  func max(a, b Int) Int {
    21  	if a > b {
    22  		return a
    23  	}
    24  	return b
    25  }
    26  
    27  // Flatten all overlapping intervals, storing originals as sub-intervals.
    28  func Flatten(t *interval.Tree) {
    29  	var (
    30  		fi  = true
    31  		ti  []Interval
    32  		mid uintptr
    33  	)
    34  
    35  	t.Do(
    36  		func(e interval.Interface) (done bool) {
    37  			iv := e.(Interval)
    38  			if fi || iv.start >= ti[len(ti)-1].end {
    39  				ti = append(ti, Interval{
    40  					start: iv.start,
    41  					end:   iv.end,
    42  				})
    43  				fi = false
    44  			} else {
    45  				ti[len(ti)-1].end = max(ti[len(ti)-1].end, iv.end)
    46  			}
    47  			ti[len(ti)-1].Sub = append(ti[len(ti)-1].Sub, iv)
    48  			if iv.id > mid {
    49  				mid = iv.id
    50  			}
    51  
    52  			return
    53  		},
    54  	)
    55  
    56  	mid++
    57  	t.Root, t.Count = nil, 0
    58  	for i, iv := range ti {
    59  		iv.id = uintptr(i) + mid
    60  		t.Insert(iv, true)
    61  	}
    62  	t.AdjustRanges()
    63  }
    64  
    65  func ExampleTree_Do() {
    66  	t := &interval.Tree{}
    67  	for i, iv := range ivs {
    68  		iv.id = uintptr(i)
    69  		err := t.Insert(iv, false)
    70  		if err != nil {
    71  			fmt.Println(err)
    72  		}
    73  	}
    74  
    75  	Flatten(t)
    76  	t.Do(func(e interval.Interface) (done bool) { fmt.Printf("%s: %v\n", e, e.(Interval).Sub); return })
    77  
    78  	// Output:
    79  	// [0,8)#10: [[0,2)#0 [1,6)#2 [1,3)#4 [2,4)#1 [3,4)#3 [4,6)#5 [5,8)#6 [5,7)#8 [6,8)#7]
    80  	// [8,9)#11: [[8,9)#9]
    81  }