├── README.md ├── compression └── lzw │ ├── reader.go │ └── writer.go ├── concurrency ├── cond.go ├── semaphore.go ├── spinlock.go └── waitgroup.go ├── examples ├── .DS_Store ├── compression │ ├── lzw-reader-test.go │ └── lzw-writer-test.go ├── search │ ├── bfs-test.go │ ├── dfs-test.go │ └── pagerank-test.go ├── sort │ └── heapsort-test.go ├── testdata │ ├── e.txt │ └── pi.txt └── trees │ └── avl-tree-test.go ├── search ├── astar.go ├── bfs.go ├── binary-search.go ├── dfs.go └── pagerank.go ├── sort ├── bubblesort.go ├── countsort.go ├── heapsort.go ├── insertionsort.go ├── mergesort.go ├── quicksort.go ├── selectionsort.go └── shellsort.go └── trees ├── avl-tree.go ├── btree.go └── kd-tree.go /README.md: -------------------------------------------------------------------------------- 1 | # Google Go Programming Language Algorithms 2 | 3 | ![alt text](https://blog.golang.org/gopher/gopher.png "golang Gopher") 4 | 5 | Here is a collection of various Computer Science related algorithms for the Go programming language a.k.a. golang. 6 | 7 | Much of the code is from RosettaCode and standard lib, and is referenced within the file as required. 8 | 9 | Examples are available inside the [examples folder](https://github.com/gophergala/go-algos/tree/master/examples) 10 | 11 | ### Table of Contents 12 | **[Sorting](#sorting)** 13 | **[Compression](#compression)** 14 | **[Trees](#trees)** 15 | **[Artificial Intelligence](#artificial-intelligence)** 16 | **[Search](#search)** 17 | **[Concurrency](#concurrency)** 18 | 19 | ## Sorting 20 | 1. BubbleSort 21 | 2. QuickSort 22 | 3. InsertionSort 23 | 4. MergeSort 24 | 5. CountSort 25 | 6. SelectionSort 26 | 7. ShellSort 27 | 8. HeapSort 28 | 29 | ## Compression 30 | 1. Lempel–Ziv–Welch (LZW) 31 | 2. Burrows–Wheeler Transform (BWT) 32 | 3. Huffman Encodings 33 | 34 | ## Trees 35 | 1. B+ Tree 36 | 2. AVL-Tree 37 | 3. KD-Tree 38 | 39 | ## Artificial Intelligence 40 | 1. A\* Search 41 | 2. Bayesian Networks 42 | 3. Neural Networks 43 | 4. Decision Tree 44 | 45 | ## Search 46 | 1. Page-Rank 47 | 2. Depth-First Search 48 | 3. Breadth-First Search 49 | 4. Binary Search 50 | 51 | ## Concurrency Locks 52 | 1. WaitGroup (Barrier) 53 | 2. Mutex Lock 54 | 3. Semaphore 55 | 4. Condition Variable 56 | 5. Spin Lock 57 | -------------------------------------------------------------------------------- /compression/lzw/reader.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 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 | 5 | // Package lzw implements the Lempel-Ziv-Welch compressed data format, 6 | // described in T. A. Welch, ``A Technique for High-Performance Data 7 | // Compression'', Computer, 17(6) (June 1984), pp 8-19. 8 | // 9 | // In particular, it implements LZW as used by the GIF and PDF file 10 | // formats, which means variable-width codes up to 12 bits and the first 11 | // two non-literal codes are a clear code and an EOF code. 12 | // 13 | // The TIFF file format uses a similar but incompatible version of the LZW 14 | // algorithm. See the golang.org/x/image/tiff/lzw package for an 15 | // implementation. 16 | 17 | // Source: https://golang.org/src/compress/lzw/reader.go 18 | package lzw 19 | 20 | // TODO(nigeltao): check that PDF uses LZW in the same way as GIF, 21 | // modulo LSB/MSB packing order. 22 | 23 | import ( 24 | "bufio" 25 | "errors" 26 | "fmt" 27 | "io" 28 | ) 29 | 30 | // Order specifies the bit ordering in an LZW data stream. 31 | type Order int 32 | 33 | const ( 34 | // LSB means Least Significant Bits first, as used in the GIF file format. 35 | LSB Order = iota 36 | // MSB means Most Significant Bits first, as used in the TIFF and PDF 37 | // file formats. 38 | MSB 39 | ) 40 | 41 | const ( 42 | maxWidth = 12 43 | decoderInvalidCode = 0xffff 44 | flushBuffer = 1 << maxWidth 45 | ) 46 | 47 | // decoder is the state from which the readXxx method converts a byte 48 | // stream into a code stream. 49 | type decoder struct { 50 | r io.ByteReader 51 | bits uint32 52 | nBits uint 53 | width uint 54 | read func(*decoder) (uint16, error) // readLSB or readMSB 55 | litWidth int // width in bits of literal codes 56 | err error 57 | 58 | // The first 1<= 1<>= d.width 98 | d.nBits -= d.width 99 | return code, nil 100 | } 101 | 102 | // readMSB returns the next code for "Most Significant Bits first" data. 103 | func (d *decoder) readMSB() (uint16, error) { 104 | for d.nBits < d.width { 105 | x, err := d.r.ReadByte() 106 | if err != nil { 107 | return 0, err 108 | } 109 | d.bits |= uint32(x) << (24 - d.nBits) 110 | d.nBits += 8 111 | } 112 | code := uint16(d.bits >> (32 - d.width)) 113 | d.bits <<= d.width 114 | d.nBits -= d.width 115 | return code, nil 116 | } 117 | 118 | func (d *decoder) Read(b []byte) (int, error) { 119 | for { 120 | if len(d.toRead) > 0 { 121 | n := copy(b, d.toRead) 122 | d.toRead = d.toRead[n:] 123 | return n, nil 124 | } 125 | if d.err != nil { 126 | return 0, d.err 127 | } 128 | d.decode() 129 | } 130 | } 131 | 132 | // decode decompresses bytes from r and leaves them in d.toRead. 133 | // read specifies how to decode bytes into codes. 134 | // litWidth is the width in bits of literal codes. 135 | func (d *decoder) decode() { 136 | // Loop over the code stream, converting codes into decompressed bytes. 137 | for { 138 | code, err := d.read(d) 139 | if err != nil { 140 | if err == io.EOF { 141 | err = io.ErrUnexpectedEOF 142 | } 143 | d.err = err 144 | return 145 | } 146 | switch { 147 | case code < d.clear: 148 | // We have a literal code. 149 | d.output[d.o] = uint8(code) 150 | d.o++ 151 | if d.last != decoderInvalidCode { 152 | // Save what the hi code expands to. 153 | d.suffix[d.hi] = uint8(code) 154 | d.prefix[d.hi] = d.last 155 | } 156 | case code == d.clear: 157 | d.width = 1 + uint(d.litWidth) 158 | d.hi = d.eof 159 | d.overflow = 1 << d.width 160 | d.last = decoderInvalidCode 161 | continue 162 | case code == d.eof: 163 | d.flush() 164 | d.err = io.EOF 165 | return 166 | case code <= d.hi: 167 | c, i := code, len(d.output)-1 168 | if code == d.hi { 169 | // code == hi is a special case which expands to the last expansion 170 | // followed by the head of the last expansion. To find the head, we walk 171 | // the prefix chain until we find a literal code. 172 | c = d.last 173 | for c >= d.clear { 174 | c = d.prefix[c] 175 | } 176 | d.output[i] = uint8(c) 177 | i-- 178 | c = d.last 179 | } 180 | // Copy the suffix chain into output and then write that to w. 181 | for c >= d.clear { 182 | d.output[i] = d.suffix[c] 183 | i-- 184 | c = d.prefix[c] 185 | } 186 | d.output[i] = uint8(c) 187 | d.o += copy(d.output[d.o:], d.output[i:]) 188 | if d.last != decoderInvalidCode { 189 | // Save what the hi code expands to. 190 | d.suffix[d.hi] = uint8(c) 191 | d.prefix[d.hi] = d.last 192 | } 193 | default: 194 | d.err = errors.New("lzw: invalid code") 195 | return 196 | } 197 | d.last, d.hi = code, d.hi+1 198 | if d.hi >= d.overflow { 199 | if d.width == maxWidth { 200 | d.last = decoderInvalidCode 201 | } else { 202 | d.width++ 203 | d.overflow <<= 1 204 | } 205 | } 206 | if d.o >= flushBuffer { 207 | d.flush() 208 | return 209 | } 210 | } 211 | } 212 | 213 | func (d *decoder) flush() { 214 | d.toRead = d.output[:d.o] 215 | d.o = 0 216 | } 217 | 218 | var errClosed = errors.New("compress/lzw: reader/writer is closed") 219 | 220 | func (d *decoder) Close() error { 221 | d.err = errClosed // in case any Reads come along 222 | return nil 223 | } 224 | 225 | // NewReader creates a new io.ReadCloser. 226 | // Reads from the returned io.ReadCloser read and decompress data from r. 227 | // If r does not also implement io.ByteReader, 228 | // the decompressor may read more data than necessary from r. 229 | // It is the caller's responsibility to call Close on the ReadCloser when 230 | // finished reading. 231 | // The number of bits to use for literal codes, litWidth, must be in the 232 | // range [2,8] and is typically 8. 233 | func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser { 234 | d := new(decoder) 235 | switch order { 236 | case LSB: 237 | d.read = (*decoder).readLSB 238 | case MSB: 239 | d.read = (*decoder).readMSB 240 | default: 241 | d.err = errors.New("lzw: unknown order") 242 | return d 243 | } 244 | if litWidth < 2 || 8 < litWidth { 245 | d.err = fmt.Errorf("lzw: litWidth %d out of range", litWidth) 246 | return d 247 | } 248 | if br, ok := r.(io.ByteReader); ok { 249 | d.r = br 250 | } else { 251 | d.r = bufio.NewReader(r) 252 | } 253 | d.litWidth = litWidth 254 | d.width = 1 + uint(litWidth) 255 | d.clear = uint16(1) << uint(litWidth) 256 | d.eof, d.hi = d.clear+1, d.clear+1 257 | d.overflow = uint16(1) << d.width 258 | d.last = decoderInvalidCode 259 | 260 | return d 261 | } -------------------------------------------------------------------------------- /compression/lzw/writer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 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 | 5 | // Source: https://golang.org/src/compress/lzw/writer.go 6 | package lzw 7 | 8 | import ( 9 | "bufio" 10 | "errors" 11 | "fmt" 12 | "io" 13 | ) 14 | 15 | // A writer is a buffered, flushable writer. 16 | type writer interface { 17 | io.ByteWriter 18 | Flush() error 19 | } 20 | 21 | // An errWriteCloser is an io.WriteCloser that always returns a given error. 22 | type errWriteCloser struct { 23 | err error 24 | } 25 | 26 | func (e *errWriteCloser) Write([]byte) (int, error) { 27 | return 0, e.err 28 | } 29 | 30 | func (e *errWriteCloser) Close() error { 31 | return e.err 32 | } 33 | 34 | const ( 35 | // A code is a 12 bit value, stored as a uint32 when encoding to avoid 36 | // type conversions when shifting bits. 37 | maxCode = 1<<12 - 1 38 | invalidCode = 1<<32 - 1 39 | // There are 1<<12 possible codes, which is an upper bound on the number of 40 | // valid hash table entries at any given point in time. tableSize is 4x that. 41 | tableSize = 4 * 1 << 12 42 | tableMask = tableSize - 1 43 | // A hash table entry is a uint32. Zero is an invalid entry since the 44 | // lower 12 bits of a valid entry must be a non-literal code. 45 | invalidEntry = 0 46 | ) 47 | 48 | // encoder is LZW compressor. 49 | type encoder struct { 50 | // w is the writer that compressed bytes are written to. 51 | w writer 52 | // order, write, bits, nBits and width are the state for 53 | // converting a code stream into a byte stream. 54 | order Order 55 | write func(*encoder, uint32) error 56 | bits uint32 57 | nBits uint 58 | width uint 59 | // litWidth is the width in bits of literal codes. 60 | litWidth uint 61 | // hi is the code implied by the next code emission. 62 | // overflow is the code at which hi overflows the code width. 63 | hi, overflow uint32 64 | // savedCode is the accumulated code at the end of the most recent Write 65 | // call. It is equal to invalidCode if there was no such call. 66 | savedCode uint32 67 | // err is the first error encountered during writing. Closing the encoder 68 | // will make any future Write calls return errClosed 69 | err error 70 | // table is the hash table from 20-bit keys to 12-bit values. Each table 71 | // entry contains key<<12|val and collisions resolve by linear probing. 72 | // The keys consist of a 12-bit code prefix and an 8-bit byte suffix. 73 | // The values are a 12-bit code. 74 | table [tableSize]uint32 75 | } 76 | 77 | // writeLSB writes the code c for "Least Significant Bits first" data. 78 | func (e *encoder) writeLSB(c uint32) error { 79 | e.bits |= c << e.nBits 80 | e.nBits += e.width 81 | for e.nBits >= 8 { 82 | if err := e.w.WriteByte(uint8(e.bits)); err != nil { 83 | return err 84 | } 85 | e.bits >>= 8 86 | e.nBits -= 8 87 | } 88 | return nil 89 | } 90 | 91 | // writeMSB writes the code c for "Most Significant Bits first" data. 92 | func (e *encoder) writeMSB(c uint32) error { 93 | e.bits |= c << (32 - e.width - e.nBits) 94 | e.nBits += e.width 95 | for e.nBits >= 8 { 96 | if err := e.w.WriteByte(uint8(e.bits >> 24)); err != nil { 97 | return err 98 | } 99 | e.bits <<= 8 100 | e.nBits -= 8 101 | } 102 | return nil 103 | } 104 | 105 | // errOutOfCodes is an internal error that means that the encoder has run out 106 | // of unused codes and a clear code needs to be sent next. 107 | var errOutOfCodes = errors.New("lzw: out of codes") 108 | 109 | // incHi increments e.hi and checks for both overflow and running out of 110 | // unused codes. In the latter case, incHi sends a clear code, resets the 111 | // encoder state and returns errOutOfCodes. 112 | func (e *encoder) incHi() error { 113 | e.hi++ 114 | if e.hi == e.overflow { 115 | e.width++ 116 | e.overflow <<= 1 117 | } 118 | if e.hi == maxCode { 119 | clear := uint32(1) << e.litWidth 120 | if err := e.write(e, clear); err != nil { 121 | return err 122 | } 123 | e.width = uint(e.litWidth) + 1 124 | e.hi = clear + 1 125 | e.overflow = clear << 1 126 | for i := range e.table { 127 | e.table[i] = invalidEntry 128 | } 129 | return errOutOfCodes 130 | } 131 | return nil 132 | } 133 | 134 | // Write writes a compressed representation of p to e's underlying writer. 135 | func (e *encoder) Write(p []byte) (n int, err error) { 136 | if e.err != nil { 137 | return 0, e.err 138 | } 139 | if len(p) == 0 { 140 | return 0, nil 141 | } 142 | n = len(p) 143 | litMask := uint32(1<>12 ^ key) & tableMask 156 | for h, t := hash, e.table[hash]; t != invalidEntry; { 157 | if key == t>>12 { 158 | code = t & maxCode 159 | continue loop 160 | } 161 | h = (h + 1) & tableMask 162 | t = e.table[h] 163 | } 164 | // Otherwise, write the current code, and literal becomes the start of 165 | // the next emitted code. 166 | if e.err = e.write(e, code); e.err != nil { 167 | return 0, e.err 168 | } 169 | code = literal 170 | // Increment e.hi, the next implied code. If we run out of codes, reset 171 | // the encoder state (including clearing the hash table) and continue. 172 | if err1 := e.incHi(); err1 != nil { 173 | if err1 == errOutOfCodes { 174 | continue 175 | } 176 | e.err = err1 177 | return 0, e.err 178 | } 179 | // Otherwise, insert key -> e.hi into the map that e.table represents. 180 | for { 181 | if e.table[hash] == invalidEntry { 182 | e.table[hash] = (key << 12) | e.hi 183 | break 184 | } 185 | hash = (hash + 1) & tableMask 186 | } 187 | } 188 | e.savedCode = code 189 | return n, nil 190 | } 191 | 192 | // Close closes the encoder, flushing any pending output. It does not close or 193 | // flush e's underlying writer. 194 | func (e *encoder) Close() error { 195 | if e.err != nil { 196 | if e.err == errClosed { 197 | return nil 198 | } 199 | return e.err 200 | } 201 | // Make any future calls to Write return errClosed. 202 | e.err = errClosed 203 | // Write the savedCode if valid. 204 | if e.savedCode != invalidCode { 205 | if err := e.write(e, e.savedCode); err != nil { 206 | return err 207 | } 208 | if err := e.incHi(); err != nil && err != errOutOfCodes { 209 | return err 210 | } 211 | } 212 | // Write the eof code. 213 | eof := uint32(1)< 0 { 219 | if e.order == MSB { 220 | e.bits >>= 24 221 | } 222 | if err := e.w.WriteByte(uint8(e.bits)); err != nil { 223 | return err 224 | } 225 | } 226 | return e.w.Flush() 227 | } 228 | 229 | // NewWriter creates a new io.WriteCloser. 230 | // Writes to the returned io.WriteCloser are compressed and written to w. 231 | // It is the caller's responsibility to call Close on the WriteCloser when 232 | // finished writing. 233 | // The number of bits to use for literal codes, litWidth, must be in the 234 | // range [2,8] and is typically 8. 235 | func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser { 236 | var write func(*encoder, uint32) error 237 | switch order { 238 | case LSB: 239 | write = (*encoder).writeLSB 240 | case MSB: 241 | write = (*encoder).writeMSB 242 | default: 243 | return &errWriteCloser{errors.New("lzw: unknown order")} 244 | } 245 | if litWidth < 2 || 8 < litWidth { 246 | return &errWriteCloser{fmt.Errorf("lzw: litWidth %d out of range", litWidth)} 247 | } 248 | bw, ok := w.(writer) 249 | if !ok { 250 | bw = bufio.NewWriter(w) 251 | } 252 | lw := uint(litWidth) 253 | return &encoder{ 254 | w: bw, 255 | order: order, 256 | write: write, 257 | width: 1 + lw, 258 | litWidth: lw, 259 | hi: 1< 0 && v == int32(delta) { 60 | // The first increment must be synchronized with Wait. 61 | // Need to model this as a read, because there can be 62 | // several concurrent wg.counter transitions from 0. 63 | raceRead(unsafe.Pointer(&wg.sema)) 64 | } 65 | } 66 | if v < 0 { 67 | panic("sync: negative WaitGroup counter") 68 | } 69 | if v > 0 || atomic.LoadInt32(&wg.waiters) == 0 { 70 | return 71 | } 72 | wg.m.Lock() 73 | if atomic.LoadInt32(&wg.counter) == 0 { 74 | for i := int32(0); i < wg.waiters; i++ { 75 | runtime_Semrelease(wg.sema) 76 | } 77 | wg.waiters = 0 78 | wg.sema = nil 79 | } 80 | wg.m.Unlock() 81 | } 82 | 83 | // Done decrements the WaitGroup counter. 84 | func (wg *WaitGroup) Done() { 85 | wg.Add(-1) 86 | } 87 | 88 | // Wait blocks until the WaitGroup counter is zero. 89 | func (wg *WaitGroup) Wait() { 90 | if raceenabled { 91 | _ = wg.m.state // trigger nil deref early 92 | raceDisable() 93 | } 94 | if atomic.LoadInt32(&wg.counter) == 0 { 95 | if raceenabled { 96 | raceEnable() 97 | raceAcquire(unsafe.Pointer(wg)) 98 | } 99 | return 100 | } 101 | wg.m.Lock() 102 | w := atomic.AddInt32(&wg.waiters, 1) 103 | // This code is racing with the unlocked path in Add above. 104 | // The code above modifies counter and then reads waiters. 105 | // We must modify waiters and then read counter (the opposite order) 106 | // to avoid missing an Add. 107 | if atomic.LoadInt32(&wg.counter) == 0 { 108 | atomic.AddInt32(&wg.waiters, -1) 109 | if raceenabled { 110 | raceEnable() 111 | raceAcquire(unsafe.Pointer(wg)) 112 | raceDisable() 113 | } 114 | wg.m.Unlock() 115 | if raceenabled { 116 | raceEnable() 117 | } 118 | return 119 | } 120 | if raceenabled && w == 1 { 121 | // Wait must be synchronized with the first Add. 122 | // Need to model this is as a write to race with the read in Add. 123 | // As a consequence, can do the write only for the first waiter, 124 | // otherwise concurrent Waits will race with each other. 125 | raceWrite(unsafe.Pointer(&wg.sema)) 126 | } 127 | if wg.sema == nil { 128 | wg.sema = new(uint32) 129 | } 130 | s := wg.sema 131 | wg.m.Unlock() 132 | runtime_Semacquire(s) 133 | if raceenabled { 134 | raceEnable() 135 | raceAcquire(unsafe.Pointer(wg)) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /examples/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gophergala/go-algos/fcba29dbdde512e9163b6a52b3831f02d822e110/examples/.DS_Store -------------------------------------------------------------------------------- /examples/compression/lzw-reader-test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 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 | // Source: https://golang.org/src/compress/lzw/reader_test 5 | package main 6 | 7 | import ( 8 | "bytes" 9 | "io" 10 | "io/ioutil" 11 | "runtime" 12 | "strconv" 13 | "strings" 14 | "testing" 15 | "github.com/gophergala/go-algos/compression/lzw" 16 | ) 17 | 18 | type lzwTest struct { 19 | desc string 20 | raw string 21 | compressed string 22 | err error 23 | } 24 | 25 | var lzwTests = []lzwTest{ 26 | { 27 | "empty;LSB;8", 28 | "", 29 | "\x01\x01", 30 | nil, 31 | }, 32 | { 33 | "empty;MSB;8", 34 | "", 35 | "\x80\x80", 36 | nil, 37 | }, 38 | { 39 | "tobe;LSB;7", 40 | "TOBEORNOTTOBEORTOBEORNOT", 41 | "\x54\x4f\x42\x45\x4f\x52\x4e\x4f\x54\x82\x84\x86\x8b\x85\x87\x89\x81", 42 | nil, 43 | }, 44 | { 45 | "tobe;LSB;8", 46 | "TOBEORNOTTOBEORTOBEORNOT", 47 | "\x54\x9e\x08\x29\xf2\x44\x8a\x93\x27\x54\x04\x12\x34\xb8\xb0\xe0\xc1\x84\x01\x01", 48 | nil, 49 | }, 50 | { 51 | "tobe;MSB;7", 52 | "TOBEORNOTTOBEORTOBEORNOT", 53 | "\x54\x4f\x42\x45\x4f\x52\x4e\x4f\x54\x82\x84\x86\x8b\x85\x87\x89\x81", 54 | nil, 55 | }, 56 | { 57 | "tobe;MSB;8", 58 | "TOBEORNOTTOBEORTOBEORNOT", 59 | "\x2a\x13\xc8\x44\x52\x79\x48\x9c\x4f\x2a\x40\xa0\x90\x68\x5c\x16\x0f\x09\x80\x80", 60 | nil, 61 | }, 62 | { 63 | "tobe-truncated;LSB;8", 64 | "TOBEORNOTTOBEORTOBEORNOT", 65 | "\x54\x9e\x08\x29\xf2\x44\x8a\x93\x27\x54\x04", 66 | io.ErrUnexpectedEOF, 67 | }, 68 | // This example comes from http://en.wikipedia.org/wiki/Graphics_Interchange_Format. 69 | { 70 | "gif;LSB;8", 71 | "\x28\xff\xff\xff\x28\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", 72 | "\x00\x51\xfc\x1b\x28\x70\xa0\xc1\x83\x01\x01", 73 | nil, 74 | }, 75 | // This example comes from http://compgroups.net/comp.lang.ruby/Decompressing-LZW-compression-from-PDF-file 76 | { 77 | "pdf;MSB;8", 78 | "-----A---B", 79 | "\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01", 80 | nil, 81 | }, 82 | } 83 | 84 | func TestReader(t *testing.T) { 85 | var b bytes.Buffer 86 | for _, tt := range lzwTests { 87 | d := strings.Split(tt.desc, ";") 88 | var order Order 89 | switch d[1] { 90 | case "LSB": 91 | order = LSB 92 | case "MSB": 93 | order = MSB 94 | default: 95 | t.Errorf("%s: bad order %q", tt.desc, d[1]) 96 | } 97 | litWidth, _ := strconv.Atoi(d[2]) 98 | rc := NewReader(strings.NewReader(tt.compressed), order, litWidth) 99 | defer rc.Close() 100 | b.Reset() 101 | n, err := io.Copy(&b, rc) 102 | if err != nil { 103 | if err != tt.err { 104 | t.Errorf("%s: io.Copy: %v want %v", tt.desc, err, tt.err) 105 | } 106 | continue 107 | } 108 | s := b.String() 109 | if s != tt.raw { 110 | t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.desc, n, s, len(tt.raw), tt.raw) 111 | } 112 | } 113 | } 114 | 115 | func benchmarkDecoder(b *testing.B, n int) { 116 | b.StopTimer() 117 | b.SetBytes(int64(n)) 118 | buf0, err := ioutil.ReadFile("../testdata/e.txt") 119 | if err != nil { 120 | b.Fatal(err) 121 | } 122 | if len(buf0) == 0 { 123 | b.Fatalf("test file has no data") 124 | } 125 | compressed := new(bytes.Buffer) 126 | w := NewWriter(compressed, LSB, 8) 127 | for i := 0; i < n; i += len(buf0) { 128 | if len(buf0) > n-i { 129 | buf0 = buf0[:n-i] 130 | } 131 | w.Write(buf0) 132 | } 133 | w.Close() 134 | buf1 := compressed.Bytes() 135 | buf0, compressed, w = nil, nil, nil 136 | runtime.GC() 137 | b.StartTimer() 138 | for i := 0; i < b.N; i++ { 139 | io.Copy(ioutil.Discard, NewReader(bytes.NewReader(buf1), LSB, 8)) 140 | } 141 | } 142 | 143 | func BenchmarkDecoder1e4(b *testing.B) { 144 | benchmarkDecoder(b, 1e4) 145 | } 146 | 147 | func BenchmarkDecoder1e5(b *testing.B) { 148 | benchmarkDecoder(b, 1e5) 149 | } 150 | 151 | func BenchmarkDecoder1e6(b *testing.B) { 152 | benchmarkDecoder(b, 1e6) 153 | } -------------------------------------------------------------------------------- /examples/compression/lzw-writer-test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 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 | // Source: https://golang.org/src/compress/lzw/writer_test 5 | 6 | package main 7 | 8 | import ( 9 | "io" 10 | "io/ioutil" 11 | "os" 12 | "runtime" 13 | "testing" 14 | "github.com/gophergala/go-algos/compression/lzw" 15 | ) 16 | 17 | var filenames = []string{ 18 | "../testdata/e.txt", 19 | "../testdata/pi.txt", 20 | } 21 | 22 | // testFile tests that compressing and then decompressing the given file with 23 | // the given options yields equivalent bytes to the original file. 24 | func testFile(t *testing.T, fn string, order Order, litWidth int) { 25 | // Read the file, as golden output. 26 | golden, err := os.Open(fn) 27 | if err != nil { 28 | t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err) 29 | return 30 | } 31 | defer golden.Close() 32 | 33 | // Read the file again, and push it through a pipe that compresses at the write end, and decompresses at the read end. 34 | raw, err := os.Open(fn) 35 | if err != nil { 36 | t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err) 37 | return 38 | } 39 | 40 | piper, pipew := io.Pipe() 41 | defer piper.Close() 42 | go func() { 43 | defer raw.Close() 44 | defer pipew.Close() 45 | lzww := NewWriter(pipew, order, litWidth) 46 | defer lzww.Close() 47 | var b [4096]byte 48 | for { 49 | n, err0 := raw.Read(b[:]) 50 | if err0 != nil && err0 != io.EOF { 51 | t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err0) 52 | return 53 | } 54 | _, err1 := lzww.Write(b[:n]) 55 | if err1 != nil { 56 | t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err1) 57 | return 58 | } 59 | if err0 == io.EOF { 60 | break 61 | } 62 | } 63 | }() 64 | lzwr := NewReader(piper, order, litWidth) 65 | defer lzwr.Close() 66 | 67 | // Compare the two. 68 | b0, err0 := ioutil.ReadAll(golden) 69 | b1, err1 := ioutil.ReadAll(lzwr) 70 | if err0 != nil { 71 | t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err0) 72 | return 73 | } 74 | if err1 != nil { 75 | t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err1) 76 | return 77 | } 78 | if len(b1) != len(b0) { 79 | t.Errorf("%s (order=%d litWidth=%d): length mismatch %d != %d", fn, order, litWidth, len(b1), len(b0)) 80 | return 81 | } 82 | for i := 0; i < len(b0); i++ { 83 | if b1[i] != b0[i] { 84 | t.Errorf("%s (order=%d litWidth=%d): mismatch at %d, 0x%02x != 0x%02x\n", fn, order, litWidth, i, b1[i], b0[i]) 85 | return 86 | } 87 | } 88 | } 89 | 90 | func TestWriter(t *testing.T) { 91 | for _, filename := range filenames { 92 | for _, order := range [...]Order{LSB, MSB} { 93 | // The test data "2.71828 etcetera" is ASCII text requiring at least 6 bits. 94 | for _, litWidth := range [...]int{6, 7, 8} { 95 | testFile(t, filename, order, litWidth) 96 | } 97 | } 98 | } 99 | } 100 | 101 | func TestWriterReturnValues(t *testing.T) { 102 | w := NewWriter(ioutil.Discard, LSB, 8) 103 | n, err := w.Write([]byte("asdf")) 104 | if n != 4 || err != nil { 105 | t.Errorf("got %d, %v, want 4, nil", n, err) 106 | } 107 | } 108 | 109 | func benchmarkEncoder(b *testing.B, n int) { 110 | b.StopTimer() 111 | b.SetBytes(int64(n)) 112 | buf0, err := ioutil.ReadFile("../testdata/e.txt") 113 | if err != nil { 114 | b.Fatal(err) 115 | } 116 | if len(buf0) == 0 { 117 | b.Fatalf("test file has no data") 118 | } 119 | buf1 := make([]byte, n) 120 | for i := 0; i < n; i += len(buf0) { 121 | if len(buf0) > n-i { 122 | buf0 = buf0[:n-i] 123 | } 124 | copy(buf1[i:], buf0) 125 | } 126 | buf0 = nil 127 | runtime.GC() 128 | b.StartTimer() 129 | for i := 0; i < b.N; i++ { 130 | w := NewWriter(ioutil.Discard, LSB, 8) 131 | w.Write(buf1) 132 | w.Close() 133 | } 134 | } 135 | 136 | func BenchmarkEncoder1e4(b *testing.B) { 137 | benchmarkEncoder(b, 1e4) 138 | } 139 | 140 | func BenchmarkEncoder1e5(b *testing.B) { 141 | benchmarkEncoder(b, 1e5) 142 | } 143 | 144 | func BenchmarkEncoder1e6(b *testing.B) { 145 | benchmarkEncoder(b, 1e6) 146 | } -------------------------------------------------------------------------------- /examples/search/bfs-test.go: -------------------------------------------------------------------------------- 1 | // Source: https://github.com/adlawson/search-algorithms/blob/master/golang/bfs_test.go 2 | package main 3 | 4 | import { 5 | "fmt" 6 | "github.com/gophergala/go-algos/search" 7 | } 8 | 9 | var nodes = map[int][]int{ 10 | 1: []int{2, 3, 4}, 11 | 2: []int{1, 5, 6}, 12 | 3: []int{1}, 13 | 4: []int{1, 7, 8}, 14 | 5: []int{2, 9, 10}, 15 | 6: []int{2}, 16 | 7: []int{4, 11, 12}, 17 | 8: []int{4}, 18 | 9: []int{5}, 19 | 10: []int{5}, 20 | 11: []int{7}, 21 | 12: []int{7}, 22 | } 23 | 24 | func main() { 25 | visited := []int{} 26 | bfs(1, nodes, func (node int) { 27 | visited = append(visited, node) 28 | }) 29 | fmt.Println(visited) 30 | } -------------------------------------------------------------------------------- /examples/search/dfs-test.go: -------------------------------------------------------------------------------- 1 | // source: https://github.com/dcadenas/pagerank/blob/master/pagerank_test.go 2 | 3 | package main 4 | 5 | import { 6 | "fmt" 7 | "github.com/gophergala/go-algos/search" 8 | 9 | } 10 | var nodes = map[int][]int{ 11 | 1: []int{2, 7, 8}, 12 | 2: []int{1, 3, 6}, 13 | 3: []int{2, 4, 5}, 14 | 4: []int{3}, 15 | 5: []int{3}, 16 | 6: []int{2}, 17 | 7: []int{1}, 18 | 8: []int{1, 9, 12}, 19 | 9: []int{8, 10, 11}, 20 | 10: []int{9}, 21 | 11: []int{9}, 22 | 12: []int{8}, 23 | } 24 | 25 | func main() { 26 | visited := []int{} 27 | dfs(1, nodes, func (node int) { 28 | visited = append(visited, node) 29 | }) 30 | fmt.Println(visited) 31 | } -------------------------------------------------------------------------------- /examples/search/pagerank-test.go: -------------------------------------------------------------------------------- 1 | 2 | // source: https://github.com/dcadenas/pagerank/blob/master/pagerank_test.go 3 | 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "math" 9 | "math/rand" 10 | "runtime" 11 | "testing" 12 | "github.com/gophergala/go-algos/search" 13 | ) 14 | 15 | func init() { 16 | runtime.GOMAXPROCS(runtime.NumCPU()) 17 | } 18 | 19 | func round(f float64) float64 { 20 | return math.Floor(f*10+0.5) / 10 21 | } 22 | 23 | func toPercentage(f float64) float64 { 24 | tenPow3 := math.Pow(10, 3) 25 | return round(100 * (f * tenPow3) / tenPow3) 26 | } 27 | 28 | func assertRank(t *testing.T, pageRank Interface, expected map[int]float64) { 29 | const tolerance = 0.0001 30 | pageRank.Rank(0.85, tolerance, func(label int, rank float64) { 31 | rankAsPercentage := toPercentage(rank) 32 | if math.Abs(rankAsPercentage - expected[label]) > tolerance { 33 | t.Error("Rank for", label, "should be", expected[label], "but was", rankAsPercentage) 34 | } 35 | }) 36 | } 37 | 38 | func assertEqual(t *testing.T, actual, expected interface{}) { 39 | if actual != expected { 40 | t.Error("Should be", expected, "but was", actual) 41 | } 42 | } 43 | 44 | func assert(t *testing.T, actual bool) { 45 | if !actual { 46 | t.Error("Should be true") 47 | } 48 | } 49 | 50 | func TestRound(t *testing.T) { 51 | assertEqual(t, round(0.6666666), 0.7) 52 | } 53 | 54 | func TestRankToPercentage(t *testing.T) { 55 | assertEqual(t, toPercentage(0.6666666), 66.7) 56 | } 57 | 58 | func TestShouldEnterTheBlock(t *testing.T) { 59 | pageRank := New() 60 | pageRank.Link(0, 1) 61 | 62 | entered := false 63 | pageRank.Rank(0.85, 0.0001, func(_ int, _ float64) { 64 | entered = true 65 | }) 66 | 67 | assert(t, entered) 68 | } 69 | 70 | func TestShouldBePossibleToRecalculateTheRanksAfterANewLinkIsAdded(t *testing.T) { 71 | pageRank := New() 72 | pageRank.Link(0, 1) 73 | assertRank(t, pageRank, map[int]float64{0: 35.1, 1: 64.9}) 74 | pageRank.Link(1, 2) 75 | assertRank(t, pageRank, map[int]float64{0: 18.4, 1: 34.1, 2: 47.4}) 76 | } 77 | 78 | func TestShouldBePossibleToClearTheGraph(t *testing.T) { 79 | pageRank := New() 80 | pageRank.Link(0, 1) 81 | pageRank.Link(1, 2) 82 | pageRank.Clear() 83 | pageRank.Link(0, 1) 84 | assertRank(t, pageRank, map[int]float64{0: 35.1, 1: 64.9}) 85 | } 86 | 87 | func TestShouldNotFailWhenCalculatingTheRankOfAnEmptyGraph(t *testing.T) { 88 | pageRank := New() 89 | pageRank.Rank(0.85, 0.0001, func(label int, rank float64) { 90 | t.Error("This should not be seen") 91 | }) 92 | } 93 | 94 | func TestShouldReturnCorrectResultsWhenHavingADanglingNode(t *testing.T) { 95 | pageRank := New() 96 | //node 2 is a dangling node because it has no outbound links 97 | pageRank.Link(0, 2) 98 | pageRank.Link(1, 2) 99 | 100 | expectedRank := map[int]float64{ 101 | 0: 21.3, 102 | 1: 21.3, 103 | 2: 57.4, 104 | } 105 | 106 | assertRank(t, pageRank, expectedRank) 107 | } 108 | 109 | func TestShouldNotChangeTheGraphWhenAddingTheSameLinkManyTimes(t *testing.T) { 110 | pageRank := New() 111 | pageRank.Link(0, 2) 112 | pageRank.Link(0, 2) 113 | pageRank.Link(0, 2) 114 | pageRank.Link(1, 2) 115 | pageRank.Link(1, 2) 116 | 117 | expectedRank := map[int]float64{ 118 | 0: 21.3, 119 | 1: 21.3, 120 | 2: 57.4, 121 | } 122 | 123 | assertRank(t, pageRank, expectedRank) 124 | } 125 | 126 | func TestShouldReturnCorrectResultsForAStarGraph(t *testing.T) { 127 | pageRank := New() 128 | pageRank.Link(0, 2) 129 | pageRank.Link(1, 2) 130 | pageRank.Link(2, 2) 131 | 132 | expectedRank := map[int]float64{ 133 | 0: 5, 134 | 1: 5, 135 | 2: 90, 136 | } 137 | 138 | assertRank(t, pageRank, expectedRank) 139 | } 140 | 141 | func TestShouldBeUniformForACircularGraph(t *testing.T) { 142 | pageRank := New() 143 | pageRank.Link(0, 1) 144 | pageRank.Link(1, 2) 145 | pageRank.Link(2, 3) 146 | pageRank.Link(3, 4) 147 | pageRank.Link(4, 0) 148 | 149 | expectedRank := map[int]float64{ 150 | 0: 20, 151 | 1: 20, 152 | 2: 20, 153 | 3: 20, 154 | 4: 20, 155 | } 156 | 157 | assertRank(t, pageRank, expectedRank) 158 | } 159 | 160 | func TestShouldReturnCorrectResultsForAConvergingGraph(t *testing.T) { 161 | pageRank := New() 162 | pageRank.Link(0, 1) 163 | pageRank.Link(0, 2) 164 | pageRank.Link(1, 2) 165 | pageRank.Link(2, 2) 166 | 167 | expectedRank := map[int]float64{ 168 | 0: 5, 169 | 1: 7.1, 170 | 2: 87.9, 171 | } 172 | 173 | assertRank(t, pageRank, expectedRank) 174 | } 175 | 176 | func TestShouldCorrectlyReproduceTheWikipediaExample(t *testing.T) { 177 | //http://en.wikipedia.org/wiki/File:PageRanks-Example.svg 178 | pageRank := New() 179 | pageRank.Link(1, 2) 180 | pageRank.Link(2, 1) 181 | pageRank.Link(3, 0) 182 | pageRank.Link(3, 1) 183 | pageRank.Link(4, 3) 184 | pageRank.Link(4, 1) 185 | pageRank.Link(4, 5) 186 | pageRank.Link(5, 4) 187 | pageRank.Link(5, 1) 188 | pageRank.Link(6, 1) 189 | pageRank.Link(6, 4) 190 | pageRank.Link(7, 1) 191 | pageRank.Link(7, 4) 192 | pageRank.Link(8, 1) 193 | pageRank.Link(8, 4) 194 | pageRank.Link(9, 4) 195 | pageRank.Link(10, 4) 196 | 197 | expectedRank := map[int]float64{ 198 | 0: 3.3, //a 199 | 1: 38.4, //b 200 | 2: 34.3, //c 201 | 3: 3.9, //d 202 | 4: 8.1, //e 203 | 5: 3.9, //f 204 | 6: 1.6, //g 205 | 7: 1.6, //h 206 | 8: 1.6, //i 207 | 9: 1.6, //j 208 | 10: 1.6, //k 209 | } 210 | 211 | assertRank(t, pageRank, expectedRank) 212 | } 213 | 214 | func BenchmarkOneMillion(b *testing.B) { 215 | n := 1000000 216 | 217 | pageRank := New() 218 | 219 | rand.Seed(5) 220 | 221 | b.ResetTimer() 222 | for i := 0; i < b.N; i++ { 223 | for from := 0; from < n; from++ { 224 | for j := 0; j < rand.Intn(400); j++ { 225 | too := rand.Intn(n) 226 | 227 | to := too 228 | if too > 800000 { 229 | to = rand.Intn(3) 230 | } 231 | 232 | pageRank.Link(from, to) 233 | } 234 | } 235 | } 236 | 237 | result := make([]float64, n) 238 | pageRank.Rank(0.85, 0.001, func(key int, val float64) { 239 | result[key] = val 240 | }) 241 | 242 | fmt.Println("5 first values are", result[0], ",", result[1], ",", result[2], ",", result[3], ",", result[4]) 243 | pageRank.Clear() 244 | } -------------------------------------------------------------------------------- /examples/sort/heapsort-test.go: -------------------------------------------------------------------------------- 1 | // source: http://rosettacode.org/wiki/Heapsort#Go 2 | // adapted to our library 3 | 4 | package main 5 | 6 | import ( 7 | "sort" 8 | "container/heap" 9 | "github.com/gophergala/go-algos/sort" 10 | "fmt" 11 | ) 12 | 13 | func main() { 14 | a := []int{170, 45, 75, -90, -802, 24, 2, 66} 15 | 16 | fmt.Println("before:", a) 17 | 18 | heapSort(sort.IntSlice(a)) 19 | 20 | fmt.Println("after: ", a) 21 | 22 | } -------------------------------------------------------------------------------- /examples/testdata/e.txt: -------------------------------------------------------------------------------- 1 | 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190115738341879307021540891499348841675092447614606680822648001684774118537423454424371075390777449920695517027618386062613313845830007520449338265602976067371132007093287091274437470472306969772093101416928368190255151086574637721112523897844250569536967707854499699679468644549059879316368892300987931277361782154249992295763514822082698951936680331825288693984964651058209392398294887933203625094431173012381970684161403970198376793206832823764648042953118023287825098194558153017567173613320698112509961818815930416903515988885193458072738667385894228792284998920868058257492796104841984443634632449684875602336248270419786232090021609902353043699418491463140934317381436405462531520961836908887070167683964243781405927145635490613031072085103837505101157477041718986106873969655212671546889570350354021234078498193343210681701210056278802351930332247450158539047304199577770935036604169973297250886876966403555707162268447162560798826517871341951246652010305921236677194325278675398558944896970964097545918569563802363701621120477427228364896134225164450781824423529486363721417402388934412479635743702637552944483379980161254922785092577825620926226483262779333865664816277251640191059004916449982893150566047258027786318641551956532442586982946959308019152987211725563475463964479101459040905862984967912874068705048958586717479854667757573205681288459205413340539220001137863009455606881667400169842055804033637953764520304024322566135278369511778838638744396625322498506549958862342818997077332761717839280349465014345588970719425863987727547109629537415211151368350627526023264847287039207643100595841166120545297030236472549296669381151373227536450988890313602057248176585118063036442812314965507047510254465011727211555194866850800368532281831521960037356252794495158284188294787610852639813955990067376482922443752871846245780361929819713991475644882626039033814418232625150974827987779964373089970388867782271383605772978824125611907176639465070633045279546618550966661856647097113444740160704626215680717481877844371436988218559670959102596862002353718588748569652200050311734392073211390803293634479727355955277349071783793421637012050054513263835440001863239914907054797780566978533580489669062951194324730995876552368128590413832411607226029983305353708761389396391779574540161372236187893652605381558415871869255386061647798340254351284396129460352913325942794904337299085731580290958631382683291477116396337092400316894586360606458459251269946557248391865642097526850823075442545993769170419777800853627309417101634349076964237222943523661255725088147792231519747780605696725380171807763603462459278778465850656050780844211529697521890874019660906651803516501792504619501366585436632712549639908549144200014574760819302212066024330096412704894390397177195180699086998606636583232278709376502260149291011517177635944602023249300280401867723910288097866605651183260043688508817157238669842242201024950551881694803221002515426494639812873677658927688163598312477886520141174110913601164995076629077943646005851941998560162647907615321038727557126992518275687989302761761146162549356495903798045838182323368612016243736569846703785853305275833337939907521660692380533698879565137285593883499894707416181550125397064648171946708348197214488898790676503795903669672494992545279033729636162658976039498576741397359441023744329709355477982629614591442936451428617158587339746791897571211956187385783644758448423555581050025611492391518893099463428413936080383091662818811503715284967059741625628236092168075150177725387402564253470879089137291722828611515915683725241630772254406337875931059826760944203261924285317018781772960235413060672136046000389661093647095141417185777014180606443636815464440053316087783143174440811949422975599314011888683314832802706553833004693290115744147563139997221703804617092894579096271662260740718749975359212756084414737823303270330168237193648002173285734935947564334129943024850235732214597843282641421684878721673367010615094243456984401873312810107945127223737886126058165668053714396127888732527373890392890506865324138062796025930387727697783792868409325365880733988457218746021005311483351323850047827169376218004904795597959290591655470505777514308175112698985188408718564026035305583737832422924185625644255022672155980274012617971928047139600689163828665277009752767069777036439260224372841840883251848770472638440379530166905465937461619323840363893131364327137688841026811219891275223056256756254701725086349765367288605966752740868627407912856576996313789753034660616669804218267724560530660773899624218340859882071864682623215080288286359746839654358856685503773131296587975810501214916207656769950659715344763470320853215603674828608378656803073062657633469774295634643716709397193060876963495328846833613038829431040800296873869117066666146800015121143442256023874474325250769387077775193299942137277211258843608715834835626961661980572526612206797540621062080649882918454395301529982092503005498257043390553570168653120526495614857249257386206917403695213533732531666345466588597286659451136441370331393672118569553952108458407244323835586063106806964924851232632699514603596037297253198368423363904632136710116192821711150282801604488058802382031981493096369596735832742024988245684941273860566491352526706046234450549227581151709314921879592718001940968866986837037302200475314338181092708030017205935530520700706072233999463990571311587099635777359027196285061146514837526209565346713290025994397663114545902685898979115837093419370441155121920117164880566945938131183843765620627846310490346293950029458341164824114969758326011800731699437393506966295712410273239138741754923071862454543222039552735295240245903805744502892246886285336542213815722131163288112052146489805180092024719391710555390113943316681515828843687606961102505171007392762385553386272553538830960671644662370922646809671254061869502143176211668140097595281493907222601112681153108387317617323235263605838173151034595736538223534992935822836851007810884634349983518404451704270189381994243410090575376257767571118090088164183319201962623416288166521374717325477727783488774366518828752156685719506371936565390389449366421764003121527870222366463635755503565576948886549500270853923617105502131147413744106134445544192101336172996285694899193369184729478580729156088510396781959429833186480756083679551496636448965592948187851784038773326247051945050419847742014183947731202815886845707290544057510601285258056594703046836344592652552137008068752009593453607316226118728173928074623094685367823106097921599360019946237993434210687813497346959246469752506246958616909178573976595199392993995567542714654910456860702099012606818704984178079173924071945996323060254707901774527513186809982284730860766536866855516467702911336827563107223346726113705490795365834538637196235856312618387156774118738527722922594743373785695538456246801013905727871016512966636764451872465653730402443684140814488732957847348490003019477888020460324660842875351848364959195082888323206522128104190448047247949291342284951970022601310430062410717971502793433263407995960531446053230488528972917659876016667811937932372453857209607582277178483361613582612896226118129455927462767137794487586753657544861407611931125958512655759734573015333642630767985443385761715333462325270572005303988289499034259566232975782488735029259166825894456894655992658454762694528780516501720674785417887982276806536650641910973434528878338621726156269582654478205672987756426325321594294418039943217000090542650763095588465895171709147607437136893319469090981904501290307099566226620303182649365733698419555776963787624918852865686607600566025605445711337286840205574416030837052312242587223438854123179481388550075689381124935386318635287083799845692619981794523364087429591180747453419551420351726184200845509170845682368200897739455842679214273477560879644279202708312150156406341341617166448069815483764491573900121217041547872591998943825364950514771379399147205219529079396137621107238494290616357604596231253506068537651423115349665683715116604220796394466621163255157729070978473156278277598788136491951257483328793771571459091064841642678309949723674420175862269402159407924480541255360431317992696739157542419296607312393763542139230617876753958711436104089409966089471418340698362993675362621545247298464213752891079884381306095552622720837518629837066787224430195793793786072107254277289071732854874374355781966511716618330881129120245204048682200072344035025448202834254187884653602591506445271657700044521097735585897622655484941621714989532383421600114062950718490427789258552743035221396835679018076406042138307308774460170842688272261177180842664333651780002171903449234264266292261456004337383868335555343453004264818473989215627086095650629340405264943244261445665921291225648893569655009154306426134252668472594914314239398845432486327461842846655985332312210466259890141712103446084271616619001257195870793217569698544013397622096749454185407118446433946990162698351607848924514058940946395267807354579700307051163682519487701189764002827648414160587206184185297189154019688253289309149665345753571427318482016384644832499037886069008072709327673127581966563941148961716832980455139729506687604740915420428429993541025829113502241690769431668574242522509026939034814856451303069925199590436384028429267412573422447765584177886171737265462085498294498946787350929581652632072258992368768457017823038096567883112289305809140572610865884845873101658151167533327674887014829167419701512559782572707406431808601428149024146780472327597684269633935773542930186739439716388611764209004068663398856841681003872389214483176070116684503887212364367043314091155733280182977988736590916659612402021778558854876176161989370794380056663364884365089144805571039765214696027662583599051987042300179465536788567430285974600143785483237068701190078499404930918919181649327259774030074879681484882342932023012128032327460392219687528340516906974194257614673978110715464186273369091584973185011183960482533518748438923177292613543024932562896371361977285456622924461644497284597867711574125670307871885109336344480149675240618536569532074170533486782754827815415561966911055101472799040386897220465550833170782394808785990501947563108984124144672821865459971596639015641941751820935932616316888380132758752601460507676098392625726411120135288591317848299475682472564885533357279772205543568126302535748216585414000805314820697137262149755576051890481622376790414926742600071045922695314835188137463887104273544767623577933993970632396604969145303273887874557905934937772320142954803345000695256980935282887783710670585567749481373858630385762823040694005665340584887527005308832459182183494318049834199639981458773435863115940570443683515285383609442955964360676090221741896883548131643997437764158365242234642619597390455450680695232850751868719449064767791886720306418630751053512149851051207313846648717547518382979990189317751550639981016466414592102406838294603208535554058147159273220677567669213664081505900806952540610628536408293276621931939933861623836069111767785448236129326858199965239275488427435414402884536455595124735546139403154952097397051896240157976832639450633230452192645049651735466775699295718989690470902730288544945416699791992948038254980285946029052763145580316514066229171223429375806143993484914362107993576737317948964252488813720435579287511385856973381976083524423240466778020948399639946684833774706725483618848273000648319163826022110555221246733323184463005504481849916996622087746140216157021029603318588727333298779352570182393861244026868339555870607758169954398469568540671174444932479519572159419645863736126915526457574786985964242176592896862383506370433939811671397544736228625506803682664135541448048997721373174119199970017293907303350869020922519124447393278376156321810842898207706974138707053266117683698647741787180202729412982310888796831880854367327806879771659111654224453806625861711729498038248879986504061563975629936962809358189761491017145343556659542757064194408833816841111166200759787244137082333917886114708228657531078536674695018462140736493917366254937783014074302668422150335117736471853872324040421037907750266020114814935482228916663640782450166815341213505278578539332606110249802273093636740213515386431693015267460536064351732154701091440650878823636764236831187390937464232609021646365627553976834019482932795750624399645272578624400375983422050808935129023122475970644105678361870877172333555465482598906861201410107222465904008553798235253885171623518256518482203125214950700378300411216212126052726059944320443056274522916128891766814160639131235975350390320077529587392412476451850809163911459296071156344204347133544720981178461451077872399140606290228276664309264900592249810291068759434533858330391178747575977065953570979640012224092199031158229259667913153991561438070129260780197022589662923368154312499412259460023399472228171056603931877226800493833148980338548909468685130789292064242819174795866199944411196208730498064385006852620258432842085582338566936649849720817046135376163584015342840674118587581546514598270228676671855309311923340191286170613364873183197560812569460089402953094429119590295968563923037689976327462283900735457144596414108229285922239332836210192822937243590283003884445701383771632056518351970100115722010956997890484964453434612129224964732356126321951155701565824427661599326463155806672053127596948538057364208384918887095176052287817339462747644656858900936266123311152910816041524100214195937349786431661556732702792109593543055579732660554677963552005378304619540636971842916168582734122217145885870814274090248185446421774876925093328785670674677381226752831653559245204578070541352576903253522738963847495646255940378924925007624386893776475310102323746733771474581625530698032499033676455430305274561512961214585944432150749051491453950981001388737926379964873728396416897555132275962011838248650746985492038097691932606437608743209385602815642849756549307909733854185583515789409814007691892389063090542534883896831762904120212949167195811935791203162514344096503132835216728021372415947344095498316138322505486708172221475138425166790445416617303200820330902895488808516797258495813407132180533988828139346049850532340472595097214331492586604248511405819579711564191458842833000525684776874305916390494306871343118796189637475503362820939949343690321031976898112055595369465424704173323895394046035325396758354395350516720261647961347790912327995264929045151148307923369382166010702872651938143844844532639517394110131152502750465749343063766541866128915264446926222884366299462732467958736383501937142786471398054038215513463223702071533134887083174146591492406359493020921122052610312390682941345696785958518393491382340884274312419099152870804332809132993078936867127413922890033069995875921815297612482409116951587789964090352577345938248232053055567238095022266790439614231852991989181065554412477204508510210071522352342792531266930108270633942321762570076323139159349709946933241013908779161651226804414809765618979735043151396066913258379033748620836695475083280318786707751177525663963479259219733577949555498655214193398170268639987388347010255262052312317215254062571636771270010760912281528326508984359568975961038372157726831170734552250194121701541318793651818502020877326906133592182000762327269503283827391243828198170871168108951187896746707073377869592565542713340052326706040004348843432902760360498027862160749469654989210474443927871934536701798673920803845633723311983855862638008516345597194441994344624761123844617615736242015935078520825600604101556889899501732554337298073561699861101908472096600708320280569917042590103876928658336557728758684250492690370934262028022399861803400211320742198642917383679176232826444645756330336556777374808644109969141827774253417010988435853189339175934511574023847292909015468559163792696196841000676598399744972047287881831200233383298030567865480871476464512824264478216644266616732096012564794514827125671326697067367144617795643752391742928503987022583734069852309190464967260243411270345611114149835783901793499713790913696706497637127248466613279908254305449295528594932793818341607827091326680865655921102733746700132583428715240835661522165574998431236278287106649401564670141943713823863454729606978693335973109537126499416282656463708490580151538205338326511289504938566468752921135932220265681856418260827538790002407915892646028490894922299966167437731347776134150965262448332709343898412056926145108857812249139616912534202918139898683901335795857624435194008943955180554746554000051766240202825944828833811886381749594284892013520090951007864941868256009273977667585642598378587497776669563350170748579027248701370264203283965756348010818356182372177082236423186591595883669487322411726504487268392328453010991677518376831599821263237123854357312681202445175401852132663740538802901249728180895021553100673598184430429105288459323064725590442355960551978839325930339572934663055160430923785677229293537208416693134575284011873746854691620648991164726909428982971065606801805807843600461866223562874591385185904416250663222249561448724413813849763797102676020845531824111963927941069619465426480006761727618115630063644321116224837379105623611358836334550102286170517890440570419577859833348463317921904494652923021469259756566389965893747728751393377105569802455757436190501772466214587592374418657530064998056688376964229825501195065837843125232135309371235243969149662310110328243570065781487677299160941153954063362752423712935549926713485031578238899567545287915578420483105749330060197958207739558522807307048950936235550769837881926357141779338750216344391014187576711938914416277109602859415809719913429313295145924373636456473035037374538503489286113141638094752301745088784885645741275003353303416138096560043105860548355773946625033230034341587814634602169235079216111013148948281895391028916816328709309713184139815427678818067628650978085718262117003140003377301581536334149093237034703637513354537634521050370995452942055232078817449370937677056009306353645510913481627378204985657055608784211964039972344556458607689515569686899384896439195225232309703301037277227710870564912966121061494072782442033414057441446459968236966118878411656290355117839944070961772567164919790168195234523807446299877664824873753313018142763910519234685081979001796519907050490865237442841652776611425351538665162781316090964802801234493372427866930894827913465443931965254154829494577875758599482099181824522449312077768250830768282335001597040419199560509705364696473142448453825888112602753909548852639708652339052941829691802357120545328231809270356491743371932080628731303589640570873779967845174740515317401384878082881006046388936711640477755985481263907504747295012609419990373721246201677030517790352952793168766305099837441859803498821239340919805055103821539827677291373138006715339240126954586376422065097810852907639079727841301764553247527073788764069366420012194745702358295481365781809867944020220280822637957006755393575808086318932075864444206644691649334467698180811716568665213389686173592450920801465312529777966137198695916451869432324246404401672381978020728394418264502183131483366019384891972317817154372192103946638473715630226701801343515930442853848941825678870721238520597263859224934763623122188113706307506918260109689069251417142514218153491532129077723748506635489170892850760234351768218355008829647410655814882049239533702270536705630750317499788187009989251020178015601042277836283644323729779929935160925884515772055232896978333126427671291093993103773425910592303277652667641874842441076564447767097790392324958416348527735171981064673837142742974468992320406932506062834468937543016787815320616009057693404906146176607094380110915443261929000745209895959201159412324102274845482605404361871836330268992858623582145643879695210235266673372434423091577183277565800211928270391042391966426911155333594569685782817020325495552528875464466074620294766116004435551604735044292127916358748473501590215522120388281168021413865865168464569964810015633741255098479730138656275460161279246359783661480163871602794405482710196290774543628092612567507181773641749763254436773503632580004042919906963117397787875081560227368824967077635559869284901628768699628053790181848148810833946900016380791075960745504688912686792812391148880036720729730801354431325347713094186717178607522981373539126772812593958220524289991371690685650421575056729991274177149279608831502358697816190894908487717722503860872618384947939757440664912760518878124233683125467278331513186758915668300679210215947336858591201395360301678110413444411030903388761520488296909104689167671555373346622545575975202624771242796225983278405833585897671474205724047439720232895903726148688388003174146490203843590358527993123871042845981608996101945691646983837718267264685264869172948414153004604004299585035164101899027529366867431834955447458124140190754681607770977920579383895378192128847409929537040546962226547278807248685508046571043123854873351653070570784584243335550958221912862797205455466267099131902370311779690892786623112661337671178512943059323281605826535623848164192144732543731002062738466812351691016359252588256806438946389880872735284406462208149513862275239938938734905082625472417781702582044129853760499827899020083498387362992498125742354568439023012261733665820546785671147973065077035475620567428300187473019197310881157516777005071432012726354601912460800451608108641835539669946936947322271670748972850464195392966434725254724357659192969949061670189061433616907056148280980363243454128229968275980226694045642181328624517549652147221620839824594576613342710564957193564431561774500828376935700995419541839029151033187933907614207467028867968594985439789457300768939890070073924697461812855764662265412913204052279071212820653775058280040897163467163709024906774736309136904002615646432159560910851092445162454420141442641660181385990017417408244245378610158433361777292580611159192008414091888191208858207627011483671760749046980914443057262211104583300789331698191603917150622792986282709446275915009683226345073725451366858172483498470080840163868209726371345205439802277866337293290829914010645589761697455978409211409167684020269370229231743334499986901841510888993165125090001163719114994852024821586396216294981753094623047604832399379391002142532996476235163569009445086058091202459904612118623318278614464727795523218635916551883057930657703331498510068357135624341881884405780028844018129031378653794869614630467726914552953690154167025838032477842272417994513653582260971652588356712133519546838335349801503269359798167463231847628306340588324731228951257944267639877946713121042763380872695738609314631539148548792514028885025189788076023838995615684850391995855029256054176767663145354058496296796781349420116003325874431438746248313850214980401681940795687219268462617287403480967931949965604299190281810597603263251746405016454606266765529010639868703668263299050577706266397868453584384057673298268163448646707439990917504018892319267557518354054956017732907127219134577524905771512773358423314008356080926962298894163047287780054743798498545562870729968407382937218623831766524716090967192007237658894226186550487552614557855898773008703234726418384831040394818743616224455286163287628541175946460497027724490799275146445792982549802258601001772437840167723166802004162547244179415547810554178036773553354467030326469619447560812831933095679685582771932031205941616693902049665352189672822671972640029493307384717544753761937017882976382487233361813499414541694736549254840633793674361541081593464960431603544354737728802361047743115330785159902977771499610274627769759612488879448609863349422852847651310277926279743981957617505591300993377368240510902583759345170015340522266144077237050890044496613295859536020556034009492820943862994618834790932894161098856594954213114335608810239423706087108026465913203560121875933791639666437282836752328391688865373751335794859860107569374889645657187292540448508624449947816273842517229343960137212406286783636675845331904743954740664015260871940915743955282773904303868772728262065663129387459875317749973799293043294371763801856280061141619563942414312254397099163565102848315765427037906837175764870230052388197498746636856292655058222887713221781440489538099681072143012394693530931524054081215705402274414521876541901428386744260011889041724570537470755550581632831687247110220353727166112304857340460879272501694701067831178927095527253222125224361673343366384756590949728221809418684074238351567868893421148203905824224324264643630201441787982022116248471657468291146315407563770222740135841109076078464780070182766336227978104546331131294044833570134869585165267459515187680033395522410548181767867772152798270250117195816577603549732923724732067853690257536233971216884390878879262188202305529937132397194333083536231248870386416194361506529551267334207198502259771408638122015980894363561808597010080081622557455039101321981979045520049618583777721048046635533806616517023595097133203631578945644487800945620369784973459902004606886572701865867757842758530645706617127194967371083950603267501532435909029491516973738110897934782297684100117657987098185725131372267749706609250481876835516003714638685918913011736805218743265426063700710595364425062760458252336880552521181566417553430681181548267844169315284408461087588214317641649835663127518728182948655658524206852221830755306118393326934164459415342651778653397980580828158806300749952897558204686612590853678738603318442905510689778698417735603118111677563872589911516803236547002987989628986181014596471307916144369564690909518788574398821730583884980809523077569358851616027719521488998358632323127308909861560777386006984035267826785387215920936255817889813416247486456433211043194821421299793188104636399541496539441501383868748384870224681829391860319598667962363489309283087840712400431022706137591368056518861313458307990705003607588327248867879324093380071864152853317943535073401891193638546730000660453783784472469288830546979000131248952100446949032058838294923613919284305249167833012980192255157050378521810552961623637523647962685751660066539364142273063001648652613891842243501797455993616794063303522111829071597538821839777552812981538570168702202620274678647916644030729018445497956399844836807851997088201407769199261674991148329821854382718946282165387064858588646221611410343570342878862979083418871606214430014533275029715104673156021000043869510583773779766003460887624861640938645252177935289947578496255243925598620521409052346250847830487046492688313289470553891357290706967599556298586669559721686506052072801342104355762779184021797626656484580261591407173477009039475168017709900129391137881248534255949312866653465033728846390649968460644741907524313323903404908195233044389559060547854954620263256676813262435925020249516275607080900436460421497025691488555265022810327762115842282433269528629137662675481993546118143913367579700141255870143319434764035725376914388899683088262844616425575034001428982557620386364384137906519612917777354183694676232982904981261717676191554292570438432239918482261744350470199171258214687683172646078959690569981353264435973965173473319484798758064137926885413552523275720457329477215706850016950046959758389373527538622664943456437071610511521617176237598050900553232154896062817794302268640579555845730600598376482703339859420098582351400179507104569019191359062304102336798080907240196312675268916362136351032648077232914950859151265812143823371072949148088472355286394195993455684156344577951727033374238129903260198160571971183950662758220321837136059718025940870615534713104482272716848395524105913605919812444978458110854511231668173534838253724825347636777581712867205865148285317273569069839935110763432091319780314031658897379628301178409806410175016511072932907832177487566289310650383806093372841399226733384778203302020700517188941706465146238366720632742644336612174011766914919235570905644803016342294301837655263108450172510307540942604409687066288066265900569082451407632599158164499361455172452057020443093722305550217222299706209749268609762787409626448772056043078634808885709143464793241536214303199965695610753570417207285334250171325558818113295504095217830139465216436594262960768570585698507157151317262928960072587601564840556088613165411835958628710665496282599535127193244635791046554389165150954187306071015034430609582302257455974944275067630926322529966338219395202927917973247094559691016402983683080426309910481567503623509654924302589575273521412445149542462972258510120707802110188106722347972579330653187713438466713807546383471635428854957610942841898601794658721444495198801550804042506452191484989920400007310672369944655246020908767882300064337725657385010969899058191290957079866699453765080407917852438222041070599278889267745752084287526377986730360561230710723922581504781379172731261234878334034473833573601973235946604273704635201327182592410906040097638585857716958419563109577748529579836844756803121874818202833941887076311731615289811756429711334181497218078040465077657204457082859417475114926179367379999220181789399433337731146911970737861041963986422166045588965683206701337505745038872111332436739840284188639147633491695114032583475841514170325690161784931455706904169858050217798497637014758914810543205854914100662201721719726878930012101267481270235940855162601689425111458499658315589660460091525797881670384625905383256920520425791378948827579603278877535466861441826827797651258953563761485994485049706638406266121957141911063246061774180577212381659872472432252969098533628440799030007594546281549235506086481557928961969617060715201589825299772803520002610888814176506636216905928021516429198484077446143617891415191517976537848282687018750030264867608433204658525470555882410254654806040437372771834769014720664234434374255514129178503032471263418076525187802925534774001104853996960549926508093910691337614841834884596365621526610332239417467064368340504749943339802285610313083038484571294767389856293937641914407036507544622061186499127249643799875806537850203753189972618014404667793050140301580709266213229273649718653952866567538572115133606114457222800851183757899219543063413692302293139751143702404830227357629039911794499248480915071002444078482866598579406525539141041497342780203520135419925977628178182825372022920108186449448349255421793982723279357095828748597126780783134286180750497175747373730296280477376908932558914598141724852658299510882230055223242218586191394795184220131553319634363922684259164168669438122537135960710031743651959027712571604588486044820674410935215327906816032054215967959066411120187618531256710150212239401285668608469435937408158536481912528004920724042172170913983123118054043277015835629513656274610248827706488865037765175678806872498861657094846665770674577000207144332525555736557083150320019082992096545498737419756608619533492312940263904930982014700371161829485939931199955070455381196711289367735249958182011774799788636393286405807810818657337668157893827656450642917396685579555053188715314552353070355994740186225988149854660737787698781542360397080977412361518245964026869979609564523828584235953564615185448165799966460648261396618720304839119560250381111550938420209894591555760083897989949964566262540514195610780090298667014635238532066032574466820259430618801773091109212741138269148784355679352572808875543164693077235363768226036080174040660997151176880434927489197133087822951123746632635635328517394189466510943745768270782209928468034684157443127739811044186762032954475468077511126663685479944460934809992951875666499902261686019672053749149951226823637895865245462813439289338365156536992413109638102559114643923805213907862893561660998836479175633176725856523591069520326895990054884753424160586689820067483163174286329119633399132709086065074595260357157323069712106423424081597068328707624437165532750228797802598690981111226558888151520837482450034463046505984569690276166958278982913613535306291331427881888249342136442417833519319786543940201465328083410341785272489879050919932369270996567133507711905899945951923990615156165480300145359212550696405345263823452155999210578191371030188979206408883974767667144727314254467923500524618849237455307575734902707342496298879996942094595961008702501329453325358045689285707241207965919809225550560061971283541270202072583994171175520920820151096509526685113897577150810849443508285458749912943857563115668324566827992991861539009255871716840495663991959154034218364537212023678608655364745175654879318925644085274489190918193411667583563439758886046349413111875241038425467937999203546910411935443113219136068129657568583611774564654674861061988591414805799318725367531243470335482637527081353105570818049642498584646147973467599315946514787025065271083508782350656532331797738656666181652390017664988485456054961300215776115255813396184027067814900350252876823607822107397102339146870159735868589015297010347780503292154014359595298683404657471756232196640515401477953167461726208727304820634652469109953327375561090578378455945469160223687689641425960164689647106348074109928546482353083540132332924864037318003195202317476206537726163717445360549726690601711176761047774971666890152163838974311714180622222345718567941507299526201086205084783127474791909996889937275229053674785020500038630036526218800670926674104806027341997756660029427941090400064654281074454007616429525362460261476180471744322889953285828397762184600967669267581270302806519535452053173536808954589902180783145775891280203970053633193821100095443241244197949192916205234421346395653840781209416214835001155883618421164283992454027590719621537570187067083731012246141362048926555668109467076386536083015847614512581588569610030337081197058344452874666198891534664244887911940711423940115986970795745946337170243268484864632018986352827092313047089215684758207753034387689978702323438584381125011714013265769320554911860153519551654627941175593967947958810333935413289702528893533748106257875620364294270257512121137330213811951395756419122685155962476203282038726342066227347868223036522019655729325905068134849292299647248229359787842720945578267329975853818536442370617353517653060396801087899490506654491544577952166038552398013798104340564182403396162494910454712104839439200945914647542424785991096900046541371091630096785951563947332190934511838669964622788855817353221326876634958059123761251203010983867841195725887799206041260049865895027247133146763722204388398558347770112599424691208308595666787531942465131444389971195968105937957532155524204659410081418351120174196853432672343271868099625045432475688702055341969199545300952644398446384346598830418262932239295612610045884644244285011551557765935780379565026806130721758672048541797157896401554276881090475899564605488362989140226580026134158039480357971019004151547655018391755772677897148793477372747525743898158705040701968215101218826088040084551332795162841280679678965570163917067779841529149397403158167896865448841319046368332179115059107813898261026271979696826411179918656038993895418928488851750122504754778999508544083983800725431468842988412616042682248823097788556495765424017114510393927980290997604904428832198976751320535115230545666467143795931915272680278210241540629795828828466355623580986725638200565215519951793551069127710538552661926903526081367717666435071213453983711357500975854405939558661737828297120544693182260401670308530911657973113259516101749193468250063285777004686987177255226525708428745733039859744230639751837209975339055095883623642814493247460522424051972825153787541962759327436278819283740253185668545040893929401040561666867664402868211607294830305236465560955351079987185041352121321534713770667681396211443891632403235741573773787908838267618458756361026435182951815392455211729022985278518025598478407179607904114472041476091765804302984501746867981277584971731733287305281134969591668387877072315968334322509070204019030503595891994666652037530271923764252552910347950343816357721698115464329245608951158732012675424975710520894362639501382962152214033621065422821876739580121286442788547491928976959315766891987305176388698461503354594898541849550251690616888419122873385522699976822609645007504500096116866129171093180282355042553653997166054753907348915189650027442328981181709248273610863801576007240601649547082331349361582435128299050405405333992577071321011503713898695076713447940748097845416328110406350804863393555238405735580863718763530261867971725608155328716436111474875107033512913923595452951407437943144900950809932872153235195999616750297532475931909938012968640379783553559071355708369947311923538531051736669154087312467233440702525006918026747725078958903448856673081487299464807786497709361969389290891718228134002845552513917355978456150353144603409441211512001738697261466786933733154341007587514908295822756919350542184106448264951943804240543255345965248373785310657979037977505031436474651422484768831323479762673689855474944277949916560108528257618964374464656819789319422077536824661110427671936481836360534108748971066866318805026555929568123959680449295166615409802610781691689418764353363449482900125929366840591370059526914934421861891742142561071896846626335874414976973921566392767687720145153302241853125308442727245771161505550519076276250016522166274796257424425420546785767478190959486500575711016264847833741198041625940813327229905891486422127968042984725356237202887830051788539737909455265135144073130049869453403245984236934627060242579432563660640597549471239092372458126154582526667304702319359866523378856244229188278436440434628094888288712101968642736370461639297485616780079779959696843367730352483047478240669928277140069031660709951473154191919911453182543906294573298686613524886500574780251977607442660798300291573030523199052185718628543687577860915726925232573171665625274275808460620177046433101212443409281314659760221360416223031167750085960128475289259463348312408766740128170543067985261868949895004918275008304998926472034986965363326210919830621495095877228260815566702155693484634079776879525038204442326697479264829899016938511552124688935873289878336267819361764023681714606495185508780596635354698788205094762016350757090024201498400967867845405354130050482404996646978558002628931826518708714613909521454987992300431779500489569529280112698632533646737179519363094399609176354568799002814515169743717518330632232942199132137614506411391269837128970829395360832883050256072727563548374205497856659895469089938558918441085605111510354367477810778500572718180809661542709143010161515013086522842238721618109043183163796046431523184434669799904865336375319295967726080853457652274714047941973192220960296582500937408249714373040087376988068797038047223488825819819025644086847749767508999164153502160223967816357097637814023962825054332801828798160046910336602415904504637333597488119998663995617171089911809851197616486499233594328274275983382931099806461605360243604040848379619072542165869409486682092396143083817303621520642297839982533698027039931804024928814430649614747600087654305571672697259114631990688823893005380061568007730984416061355843701277573463708822073792921409548717956947854414951731561828176343929570234710460088230637509877521391223419548471196982303169544468045517922669260631327498272520906329003279972932906827204647650366969765227673645419031639887433042226322021325368176044169612053532174352764937901877252263626883107879345194133825996368795020985033021472307603375442346871647223795507794130304865403488955400210765171630884759704098331306109510294140865574071074640401937347718815339902047036749084359309086354777210564861918603858715882024476138160390378532660185842568914109194464566162667753712365992832481865739251429498555141512136758288423285957759412684479036912662015308418041737698963759002546999454131659341985624780714434977201991702665380714107259910648709897259362243300706760476097690456341576573395549588448948093604077155688747288451838106069038026528318275560395905381507241627615047252487759578650784894547389096573312763852962664517004459626327934637721151028545472312880039058405918498833810711366073657536918428084655898982349219315205257478363855266205400703561310260405145079325925798227406012199249391735122145336707913500607486561657301854049217477162051678486507913573336334257685988361252720250944019430674728667983441293018131344299088234006652915385763779110955708000600143579956351811596764725075668367726052352939773016348235753572874236648294604770429166438403558846422370760111774821079625901180265548868995181239470625954254584491340203400196442965370643088660925268811549596291166168612036195319253262662271108142149856132646467211954801142455133946382385908540917878668826947602781853283155445565265933912487885639504644196022475186011405239187543742526581685003052301877096152411653980646785444273124462179491306502631062903402737260479940181929954454297256377507172705659271779285537195547433852182309492703218343678206382655341157162788603990157495208065443409462446634653253581574814022471260618973060860559065082163068709634119751925774318683671722139063093061019303182326666420628155129647685313861018672921889347039342072245556791239578260248978371473556820782675452142687314252252601795889759116238720807580527221031327444754083319215135934526961397220564699247718289310588394769170851420631557192703636345039529604362885088555160008371973526383838996789184600327073682083234847108471706160879195227388252347506380811606090840124222431476103563328940609282430125462013806032608121942876847907192546246309055749298781661271916548229644317263587524548607563020667656942355342774617635549231817456159185668061686428714964129290560130053913469569829490891003991259088290348791943368696942620662946948514931472688923571615032405542263391673583102728579723061998175868700492227418629077079508809336215346303842967525604369606110193842723883107587771653594778681499030978765900869583480043137176832954871752604714113064847270887246697164585218774442100900090916189819413456305028950484575822161887397443918833085509908566008543102796375247476265353031558684515120283396640547496946343986288291957510384781539068343717740714095628337554413567955424664601335663617305811711646062717854078898495334329100315985673932305693426085376230981047171826940937686754301837015557540822371538037838383342702379535934403549452173960327095407712107332936507766465603712364707109272580867897181182493799540477008369348889220963814281561595610931815183701135104790176383595168144627670903450457460997444500166918675661035889313483800512736411157304599205955471122443903196476642761038164285918037488354360663299436899730090925177601162043761411616688128178292382311221745850238080733727204908880095181889576314103157447684338100457385008523652069340710078955916549813037292944462306371284357984809871964143085146878525033128989319500645722582281175483887671061073178169281242483613796475692482076321356427357261609825142445262515952514875273805633150964052552659776922077806644338105562443538136258941809788015677378951310313157361136026047890761945591820289365770116416881703644242694283057457471567494391573593353763114830246668754727566653059819746822346578699972291792416156043557665183382167059157867799311835820189855730344883681934418305987021880502259192818047775223884407167894780414701414651073580452021499197980812095692195622632313741870979731320870864552236740416185590793816745658234353037283309503729022429802768451559528656923189798000383061378732434546500582722712325031420712488100290697226311129067629080951145758060270806092801504406139446350643069742785469477459876821004441453438033759717384777232052065301037861326418823586036569054773343070911759152582503029410738914441818378779490613137536794654893375260322906277631983337976816641721083140551864133302224787118511817036598365960493964571491686005656771360533192423185262166760222073368844844409234470948568027905894191829969467724456269443308241243846160408284006424867072583661011433404214473683453638496544701067827313169538435919120440283949541956874453676459875488726170687163109591315801609722382049772577307454562979127906177531663252857205858766376754282917933549923678212008601904369428956102301731743150352204665675088491593025926618816581008701658499456495586855628208747248318351516339189292646558880593601275151838235485893426165223086697314511412035659916934103076974774451947043836739600076578628245472064617380804602903639144493859012422380173377038154675297645596518492676039300171943042511794045679862114630138402371099347243455794730048929825402680821621522346560274258486595687074510352794291633405915025075992398611224340312056999780516223878772230396359709132856830486160362127579561601328561866388146004722200580017580282279272167842720649966956840905752590774886105493806116954293569077377792821084159737469613143291808510446953973485067590503662391722108732333169909603363771705474725026941732982890400239372879549386540463828596742216318201530139629734398479588628632934746650690284066719018081265539973675916799759010867483920062877888531102781695087545740384607594616919584610655963327283485609570305572502494416337066573150237126843581984154103154401008430380631442183776750349813408169325201240813452285974626715177152223063741359255747513535160669108359443999692315898156732033027129284241219651936303734407981204656795322986357374589031654007016472204989445629050395873788912680565516464274460174738175296313458739390484560414203426465560422112239134631023161290836446988901247285192778589195228773637440432659264672239982186452797664826673070168802722052338600372842903155828454593854349099449420750911108532138744823216151007808922516285123275724355101999038195993350032641446053470357293073912578481757987468353429629749652545426864234949270336399427519354240001973125098882419600095766257217621860474573769577649582201796258392376391717855799468922496750179251915218219624653575570564228220399546682648329822996167217080156801080799777126517156274295763666959661983507435667132218383358509536665806605597148376773866922551603463644386269977295750658468929599809168949981898588529537874489519527097766262684177088590284321676352132630838812766335363319004134332844347630067982023716933653652880580156390360562722752187272454764258840995216482554453662083811789117725225682611478014242896970967121967502094421226279437073328703410646312100557376727450271638975234111426287828736758358819056742163061523416789476056879277154789714326222041069587947186435439940738639948986836168919377836648327137363654676901173760246643082285362494712605173293777247276797635865806019396287718060679122426813922872134061694882029506831654589707623668302556167559477498715183426989208952182644710514911419441192277010977616645850068963849426165593473112961064282379048216056210094265076173838082479030510998790719611852832556787472942907151041468948104916751035295897242381802288151276582257190705537652455285511598636421244284176256230139538669970308943645907600684938040875210854159851278070333207779865635907968462191534944587677170063778573171211036517486371634098385626541555573292664616402279791195975248525300376741774056125700303625811704838385391207273191845064713669122576415213769896260940351804147432053600369234179035440735703058314741623452840188940808983125191307741823338981880316339159565954543405777784331681162551898060409183018907512170192983622897099598983405484962284289398469847938668614293324543983592637036699355184231661615244505980576745765335552338715678211466689996845227042954589710922163652573965950289645637766038988037941517917867910675199009966139206238732318786758420544279396366759104126821843375015743069045967947046685602358283919759975285865384338189120042853787549302768972168199113340697282255535300044743958830079799736518459131437946494086272149669719100359399974735262764126125995350902609540048669398955899487421379590802893196914845826873123710180229775301190684280440780938156598081694611679374425663244656799606363751546304833112722231812338371779800439731087402647536582575657351059978314264831879619843765495877803685261751835391844920488198629786329743136948511780579298636452193232481339393090754566368038513630619718033957979522539508697432546502659123585049283028832934489284591373621624852528877442891851104093746333590660233239711922814450735588373324057814862662207486215513375036775585494138678352928273109003823116855374520901095101174796663003330352534143230024288248051396631446632656081582045216883922312025671065388459503224002320453633895521539919011035217362720909565500846486605368975498478995875596103167696587161281951919668893326641203784750417081752273735270989343717167642329956935697166213782736138899530515711822960896394055380431939398453970864418654291655853168697537052760701061488025700785387150835779480952313152747735711713643356413242974208137266896149109564214803567792270566625834289773407718710649866150447478726164249976671481383053947984958938064202886667951943482750168192023591633247099185942520392818083953020434979919361853380201407072481627304313418985942503858404365993281651941497377286729589582881907490040331593436076189609669494800067194371424058105327517721952474344983414191979918179909864631583246021516575531754156198940698289315745851842783390581029411600498699307751428513021286202539508732388779357409781288187000829944831476678183644656510024467827445695591845768068704978044824105799710771577579093525803824227377612436908709875189149049904225568041463131309240101049368241449253427992201346380538342369643767428862595140146178201810734100565466708236854312816339049676558789901487477972479202502227218169405159042170892104287552188658308608452708423928652597536146290037780167001654671681605343292907573031466562485809639550080023347676187068086526878722783177420214068980703410506200235273632267291964034093571225623659496432076928058165514428643204955256838543079254299909353199329432966018220787933122323225928276556048763399988478426451731890365879756498207607478270258861409976050788036706732268192473513646356758611212953074644777149423343867876705824452296605797007134458987594126654609414211447540007211790607458330686866231309155780005966522736183536340439991445294960728379007338249976020630448806064574892740547730693971337007962746135534442514745423654662752252624869916077111131569725392943756732215758704952417232428206555322808868670153681482911738542735797154157943689491063759749151524510096986573825654899585216747260540468342338610760823605782941948009334370046866568258579827323875158302566720152604684361412652956519894291184887986819088277339147282063794512260294515707367105637720023427811802621502691790400488001808901847311751199425460594416773315777951735444490965752131026306836047140331442314298077895617051256930051804287472368435536402764392777908638966566390166776625678575354239947427919442544664643315554138265543388487778859972063679660692327601733858843763144148113561693030468420017434061395220072403658812798249143261731617813894970955038369479594617979829257740992171922783223006387384996138434398468502234780438733784470928703890536420557474836284616809363650973790900204118525835525201575239280826462555785658190226958376345342663420946214426672453987171047721482128157607275305173330963455909323664528978019175132987747952929099598069790148515839540444283988381797511245355548426126784217797728268989735007954505834273726937288386902125284843370917479603207479554080911491866208687184899550445210616155437083299502854903659617362726552868081324793106686855857401668022408227992433394360936223390321499357262507480617409173636062365464458476384647869520547719533384203403990244761056010612777546471464177412625548519830144627405538601855708359981544891286863480720710061787059669365218674805943569985859699554089329219507269337550235821561424994538234781138316591662683103065194730233419384164076823699357668723462219641322516076261161976034708844046473083172682611277723613381938490606534404043904909864126903479263503943531836741051762565704797064478004684323069430241749029731181951132935746854550484711078742905499870600373983113761544808189067620753424526993443755719446665453524088287267537759197074526286322840219629557247932987132852479994638938924943286917770190128914220188747760484939855471168524810559991574441551507431214406120333762869533792439547155394213121021954430556748370425907553004950664994802614794524739012802842646689229455664958621308118913500279654910344806150170407268010067948926855360944990373928383520627992820181576427054962997401900837493444950600754365525758905546552402103412862124809003162941975876195941956592556732874237856112669741771367104424821916671499611728903944393665340294226514575682907490402153401026923964977275904729573320027982816062130523130658731513076913832317193626664465502290735017347656293033318520949298475227462534564256702254695786484819977513326393221579478212493307051107367474918016345667888810782101151826314878755138027101379868751299375133303843885631415175908928986956197561123025310875057188962535763225834275763348421016668109884514141469311719314272028007223449941999003964948245457520704922091620614222912795322688239046498239081592961111003756999529251250673688233852648213896986384052437049402152187547825163347082430303521036927849762517317825860862215614519165573478940019558704784741658847364803865995119651409542615026615147651220820245816010801218275982577477652393859159165067449846149161165153821266726927461290533753163055654440793427876550267301214578324885948736899073512166118397877342715872870912311383472485146035661382188014840560716074652441118841800734067898587159273982452147328317214621907330492060817440914125388918087968538960627860118193099489240811702350413554126823863744341209267781729790694714759018264824761112414556423937732224538665992861551475342773370683344173073150805440138894084087253197595538897613986400165639906934600670780501058567196636796167140097031535132386972899001749862948883362389858632127176571330142071330179992326381982094042993377790345261665892577931395405145369730429462079488033141099249907113241694504241391265397274078984953073730364134893688060340009640631540701820289244667315059736321311926231179142794944897281477264038321021720718017561601025111179022163703476297572233435788863537030535008357679180120653016668316780269873860755423748298548246360981608957670421903145684942967286646362305101773132268579232832164818921732941553151386988781837232271364011755881332524294135348699384658137175857614330952147617551708342432434174779579226338663454959438736807839569911987059388085500837507984051126658973018149321061950769007587519836861526164087252594820126991923916722273718430385263107266000047367872474915828601694439920041571102706081507270147619679971490141639274282889578424398001497985658130305740620028554097382687819891158955487586486645709231721825870342960508203415938806006561845735081804032347750084214100574577342802985404049555529215986404933246481040773076611691605586804857302606467764258503301836174306413323887707999698641372275526317649662882467901094531117120243890323410259937511584651917675138077575448307953064925086002835629697045016137935696266759775923436166369375035368699454550392874449940328328128905560530091416446608691247256021455381248285307613556149618444364923014290938289373215312818797541139219415606631622784836152140668972661027123715779503062132916001988806369127647416567067485490795342762338253943990022498972883660263920518704790601584084302914787302246651371144395418253441269003331181914268070735159284180415100555199146564934872796969351992963117195821262627236458009708099166752820365818699111948365866102758375863322993225541477479210421324166848264953111826527351008031659958888814809945737293785681411438021523876706455063233067233939551964260397443829874822322662036352861302543796600943104500158604854027036789711934695579989189112302233381602302236277726084846296189550730850698061500281436425336666311433321645213882557346329366870956708432252564333895997812402164189946978348320376011613913855499933990786652305860332060641949298931012423081105800169745975038516887112037747631577311831360002742502722451570906304496369230938382329175076469684003556425503797106891999812319602533733677437970687713814747552190142928586781724044248049323750330957002929126630316970587409214456472022710796484778657310660832173093768033821742156446602190335203981531618935787083561603302255162155107179460621892674335641960083663483835896703409115513087820138723494714321400450513941428998350576038799343355677628023346565854351219361896876831439866735726040869511136649881229957801618882834124004126142251475184552502502640896823664946401177803776799157180146386554733265278569418005501363433953502870836220605121839418516239153709790768084909674194289061134979961034672077354959593868862427986411437928435620575955500144308051267664432183688321434583708549082240014585748228606859593502657405750939203135881722442164955416889785558265198046245527898343289578416968890756237467281044803018524217706136533236073856228166664597654076844715963930782091017090763377917711485205493367936868430832404126789220929930411890501756484917499452393770674524578019171841679541825554377930299249277892416277257788147974770446005423669346157135208417428211847353652367573702352791459837645712257646122605628127852169580892808988394594406165340521932514843306105322700231133680378433377389724881307874325614952744243584753011150345103737688223837573804282007358586938044331529253129961025096113761670187568525921208929131354473196308440066835155160913925692912175784379179004808848023029304392630921342768601226558630456913133560978156776098711809238440656353136182676923761613389237802972720736243967239854144480757286813436768000573823963610796223140429490728058551444771338682314499547929338131259971996894072233847404542592316639781608209399269744676323921370773991899853301483814622364299493902073285072098040905300059160091641710175605409814301906444379905831277826625762288108104414704097708248077905168225857235732665234414956169007985520848841886027352780861218049418060017941147110410688703738674378147161236141950474056521041002268987858525470689031657094677131822113205505046579701869337769278257145248837213394613987859786320048011792814546859096532616616068403160077901584946840224344163938313618742275417712170336151163782359059685168880561304838542087505126933144171705880517278127917564053282929427357971823360842784676292324980318169828654166132873909074116734612367109059236155113860447246378721244612580406931724769152219217409096880209008801535633471775664392125733993165330324425899852598966724744126503608416484160724482125980550754851232313331300621490042708542735985913041306918279258584509440150719217604794274047740253314305451367710311947544521321732225875550489799267468541529538871443696399406391099267018219539890685186755868574434469213792094590683677929528246795437302263472495359466300235998990248299853826140395410812427393530207575128774273992824866921285637240069184859771126480352376025469714309316636539718514623865421671429236191647402172547787238964043145364190541101514371773797752463632741619269990461595895793940622986041489302535678633503526382069821487003578061101552210224486633247184367035502326672749787730470216165019711937442505629639916559369593557640005236360445141148916155147776301876302136068825296274460238077523189646894043033182148655637014692476427395401909403584437251915352134557610698046469739424511797999048754951422010043090235713636892619493763602673645872492900162675597083797995647487354531686531900176427222751039446099641439322672532108666047912598938351926694497553568096931962642014042788365702610390456105151611792018698900673027082384103280213487456720062839744828713298223957579105420819286308176631987048287388639069922461848323992902685392499812367091421613488781501234093387999776097433615750910992585468475923085725368613605356762146929424264323906626708602846163376051573599050869800314239735368928435294958099434465414316189806451480849292695749412903363373410480943579407321266012450796613789442208485840536446021616517885568969302685188950832476793300404851688934411125834396590422211152736276278672366665845757559585409486248261694480201791748223085835007862255216359325125768382924978090431102048708975715033330963651576804501966025215527080352103848176167004443740572131294252820989545456276344353575741673638980108310579931697917916718271145837435222026387771805250290791645414791173616253155840768495583288190293564201219633684854080865928095131505012602919562576032932512847250469881908146475324342363863860247943921015193235101390117789997483527186469346024554247028375300033725403910085997650987642832802908445662021678362267272292737780213652404028817217012490974899454430826861772239385250883760749742195942655217301733355851389407457348144161511380845358039740277795072051893487170722955427683655826706766313911972211811528466502223383490906676554168336907959409404576472940901354356409277969379842065738891481990225399022315913388145851487225126560927576795873759207013915029216513720851137197522734365458411622066281660256333632074449918511469174455062297146086578736313585389023662557285424516018080487167823688885575325066254262367702604215835160174851981885460860036597606743233346410471991027562358645341748631726556391320606407754779439671383653877377610828300019937359760370467245737880967939894493795829602910746901609451288456550071458091887879542641820145369659962842686882363495879277007025298960996798975941955735253914237782443302746708282008722602053415292735847582937522487377937899136764642153727843553986244015856488692101644781661602962113570056638347990334049623875941092886778920270077504951511405782565295015024484968204744379710872943108541684540513016310902267112951959140520827546866418137305837933236150599142045255880213558474751516267815309465541240524091663857551298894834797423322854504140527354235070335984964593699534959698554244978249586929179182415068053002553370412778703476446244329205906832901886692400222391918714603175399666877477960121790688623311002908668305431787009355066944389131913333586368037447530664502418437136030852288582121720231274167009740351431532131803978033680228154223490183737494117973254478594157962104378787072154814091725163615415163381388912588517924237727229603497305533840942889918919161186249580560073570527227874940321250645426206304469470804277945973817146810395192821550688079136701210109944220737024613687196031491162370967939354636396448139025711768057799751751298979667073292674886430097398814873780767363792886767781170520534367705731566895899181530825761606591843760505051704242093231358724816618683821026679970982966436224723644898648976857100173643547336955619347638598187756855912376232580849341570570863450733443976604780386678461711520325115528237161469200634713570383377229877321365028868868859434051205798386937002783312365427450532283462669786446920780944052138528653384627970748017872477988461146015077617116261800781557915472305214759943058006652042710117125674185860274188801377931279938153727692612114066810156521441903567333926116697140453812010040811760123270513163743154487571768761575554916236601762880220601068655524141619314312671535587154866747899398685510873576261006923021359580838145290642217792987748784161516349497309700794368305080955621264592795333690631936594413261117944256602433064619312002953123619348034504503004315096798588111896950537335671086336886944665564112662287921812114121425167348136472449021275252555647623248505638391391630760976364990288930588053406631352470996993362568102360392264043588787550723319888417590521211390376609272658409023873553418516426444865247805763826160023858280693148922231457758783791564902227590699346481624734399733206013058796068136378152964615963260698744961105368384203105364183675373594176373955988088591188920114871545460924735613515979992999722298041707112256996310945945097765566409972722824015293663094891067963296735505830412258608050740410916678539569261234499102819759563955711753011823480304181029089719655278245770283085321733741593938595853203645590564229716679900322284081259569032886928291260139267587858284765599075828016611120063145411315144108875767081854894287737618991537664505164279985451077400771946398046265077776614053524831090497899859510873112620613018757108643735744708366215377470972660188656210681516328000908086198554303597948479869789466434027029290899143432223920333487108261968698934611177160561910681226015874410833093070377506876977485840324132474643763087889666151972556180371472590029550718424245405129246729039791532535999005557334600111693557020225722442772950263840538309433999383388018839553821540371447394465152512354603526742382254148328248990134023054550811390236768038649723899924257800315803725555410178461863478690646045865826036072306952576113184134225274786464852363324759102670562466350802553058142201552282050989197818420425028259521880098846231828512448393059455162005455907776121981297954040150653985341579053629101777939776957892084510979265382905626736402636703151957650493344879513766262192237185642999150828898080904189181015450813145034385734032579549707819385285699926238835221520814478940626889936085239827537174490903769904145555260249190126341431327373827075950390882531223536876389814182564965563294518709637484074360669912550026080424160562533591856230955376566866124027875883101021495284600804805028045254063691285010599912421270508133194975917146762267305044225075915290251742774636494555052325186322411388406191257012917881384181566918237215400893603475101448554254698937834239606460813666829750019379115061709452680984785152862123171377897417492087541064556959508967969794980679770961683057941674310519254486327358885118436597143583348756027405400165571178309126113117314169066606067613797690123141099672013123730329707678988740099317309687380126740538923612230370779727025191340850390101739924877352408881040807749924412635346413181858792480760553268122881584307471326768283097203149049868884456187976015468233715478415429742230166504759393312132256510189175368566338139736836336126010908419590215582111816677413843969205870515074254852744810154541079359513596653630049188769523677579147319184225806802539818418929888943038224766186405856591859943091324575886587044653095332668532261321209825839180538360814144791320319699276037194760191286674308615217243049852806380129834255379486287824758850820609389214668693729881191560115633701248675404205911464930888219050248857645752083363921499441937170268576222251074166230901665867067714568862793343153513505688216165112807318529333124070912343832502302341169501745502360505475824093175657701604884577017762183184615567978427541088499501610912720817913532406784267161792013428902861583277304794830971705537485109380418091491750245433432217445924133037928381694330975012918544596923388733288616144238100112755828623259628572648121538348900698511503485369544461542161283241700533583180520082915722904696365553178152398468725451306350506984981006205514844020769539324155096762680887603572463913955278222246439122592651921288446961107463586148252820017348957533954255019475442643148903233373926763409115527189768429887783617346613535388507656327107814312435018965109238453660236940276060642119384227665755210663671879603217527184404651560427289869560206997012906367847161654793068868305846508082886614111979138822898112498261434559408961813509226857611474609406147937240008842153535862052780125014270055274468359151840373309373580494342483940467505708347927948338133276237937844629209323999417593374917899786484958148818865149169302451512835579818112344900827168644548306546633975256079615935830821400021951611342337058359111545217293721664061708131602078213341260356852013161345136871600980378712556766143923146458085652084039744217352744813741215277475202259244561520365608268890193913957991844109971588312780020898275935898106482117936157951837937026741451400902833064466209280549839169261068975151083963132117128513257434964510681479694782619701483204392206140109523453209269311762298139422044308117317394338867965739135764377642819353621467837436136161591167926578700137748127848510041447845416464568496606699139509524527949914769441031612575776863713634644477006787131066832417871556281779122339077841275184193161188155887229676749605752053192594847679397486414128879475647133049543555044790277128690095643357913405127375570391806822344718167939329121448449553897728696601037841520390662890781218240141299368590465146519209198605347788576842696538459445700169758422531241268031418456268722581132040056433413524302102739213788415250475704533878002467378571470021087314693254557923134757243640544448132093266582986850659125571745568328831440322798049274104403921761438405750750288608423536966715191668510428001748971774811216784160854454400190449242294333666338347684438072624307319019363571067447363413698467328522605570126450123348367412135721830146848071241856625742852208909104583727386227300781566668914250733456373259567253354316171586533339843321723688126003809020585719930855573100508771533737446465211874481748868710652311198691114058503492239156755462142467550498676710264926176510110766876596258810039163948397811986615585196216487695936398904500383258041054420595482859955239065758108017936807080830518996468540836412752905182813744878769639548306385089756146421874889271294890398025623046812175145502330254086076115859321603465240763923593699949180470780496764486889980902123735780457040380820770357387588525976042434608851075199334470112741787878845674656640471901619633546770714090590826954225196409446319547658653032104723804625249971910690110456227579220926904132753699634145768795242244563973018311291451151322757841320376225862458224784696669785947914981610522628786944136373683125108310682898766123782697506343047263278453719024447970975017396831214493357290791648779915089163278018852504558488782722376705263811803792477835540018117452957747339714012352011459901984753358434861297092928529424139865507522507808919352104173963493428604871342370429572757862549365917805401652536330410692033704691093097588782938291296447890613200063096560747882082122140978472301680600835812336957051454650181292694364578357815608503303392466039553797630836137289498678842851139853615593352782103740733076818433040893624460576706096188294529171362940967592507631348636606011346115980434147450705511490716640635688739020690279453438236930531133440901381392849163507484449076828386687476663619303412376248380175840467851210698290605196112357188811150723607303158506622574566366740720668999061320627793994112805759798332878792144188725498543014546662945079670707688135022230580562225942983096887732856788971494623888272184647618153045844390967248232348259587963698908456664795754200195991919240707615823002328977439748112690476546256873684352229063217889227643289360535947903046811114130586348244566489159211382258867880972564351646404364328416076247766114349880319792230537889671148058968061594279189647401954989466232962162567264739015818692956765601444248501821713300527995551312539849919933907083138030214072556753022600033565715934283182650908979350869698950542635843046765145668997627989606295925119763672907762567862769469947280606094290314917493590511523235698715397127866718077578671910380368991445381484562682604003456798248689847811138328054940490519768008320299631757043011485087384048591850157264392187414592464617404735275250506783992273121600117160338604710710015235631159734711153198198710616109850375758965576728904060387168114313084172893710817412764581206119054145955378853200366615264923610030157044627231777788649806700723598889528747481372190175074700005571108178930354895017924552067329003818814068686247959272205591627902292600592107710510448103392878991286820705448979977319695574374529708195463942431669050083984398993036790655541596099324867822475424361758944371791403787168166189093900243862038610001362193667280872414291108080291896093127526202667881902085595708111853836166128848729527875143202956393295910508349687029060692838441522579419764824996318479414814660898281725690484184326061946254276693688953540732363428302189694947766126078346328490315128061501009539164530614554234923393806214007779256337619373052025699319099789404390847443596972052065999017828537676265683558625452697455260991024576619614037537859594506363227095122489241931813728141668427013096050734578659047904243852086508154491350136491698639048125666610843702294730266721499164849610746803261583352580352858275799038584091667618877199539888680431991650866887781701439663176815592262016991396613153738021294160006906947533431677802632207226265881842757216055461439677336258462997385077307751473833315101468395296411397329672457933540390136107395245686243008096720460995545708974893048753897955544443791303790422346037768729236001386569593952300768091377768847789746299699489949016141866131552200856673695770822720338936659590666350594330040363762591189195691561626122704788696510356062748423100605472091437069471661080277379848576543481249822444235828329813543645124092220896643987201997945619030397327254617823136363375927622656301565813545578319730419339269008282952718252138855126583037630477490625995514925943105307478901043009876580816508144862607975129633326675259272351611791836777128931053144471668835182920514343609292493191180249366051791485330421043899773019267686085347768149502299280938065840007311767895491286098112311307002535600347898600653805084532572431553654422067661352337408211307834360326940015926958459588297845649462271300855594293344520727007718206398887404742186697709349647758173683580193168322111365547392288184271373843690526638607662451284299368435082612881367358536293873792369928837047900484722240370919885912556341130849457067599032002751632513926694249485692320904596897775676762684224768120033279577059394613185252356456291805905295974791266162882381429824622654141067246487216174351317397697122228010100668178786776119825961537643641828573481088089988571570279722274734750248439022607880448075724807701621064670166965100202654371260046641935546165838945950143502160890185703558173661823437491622669077311800121188299737319891006060966841193266075165452741829459541189277264192546108246351931647783837078295218389645376236304858042774417907169146356546201215125418664885396161542055152375000426794253417764590821513675258479774465114750438460596325820468809667795709044645884673847481638045635188183210386594798204376334738389017759714236223057776395541011294523488098341476645559342209402059733452337956309441446698222457026367119493286653989491344225517746402732596722993581333110831711807234044326813737231209669052411856734897392234152750707954137453460386506786693396236535556479102508529284294227710593056660625152290924148057080971159783458351173168204129645967070633303569271821496292272073250126955216172649821895790908865085382490848904421755530946832055636316431893917626269931034289485184392539670922412565933079102365485294162132200251193795272480340133135247014182195618419055761030190199521647459734401211601239235679307823190770288415814605647291481745105388060109787505925537152356112290181284710137917215124667428500061818271276125025241876177485994084521492727902567005925854431027704636911098800554312457229683836980470864041706010966962231877065395275783874454229129966623016408054769705821417128636329650130416501278156397799631957412627634011130135082721772287129164002237230234809031485343677016544959380750634285293053131127965945266651960426350406454862543383772209428482543536823186182982713182489884498260285705690699045790998144649193654563259496570044689011049923939218088155626191834404362264965506449848521612498442375928443642612004256628602157801140467879662339228190804577624109076487087406157070486658398144845855803277997327929143195789110373530019873110486895656281917362036703039179710646309906285483702836118486672219457621775034511770110458001291255925462680537427727378863726783016568351092332280649908459179620305691566806180826586923920561895421631986004793961133953226395999749526798801074576466538377400437463695133685671362553184054638475191646737948743270916620098057717103475575333102702706317395612448413745782734376330101853438497450236265733191742446567787499665000938706441886733491099877926005340862442833450486907338279348425305698737469497333364267191968992849534561045719338665222471536681145666596959735075972188416698767321649331898967182978657974612216573922404856900225324160367805329990925438960169901664189038843548375648056012628830409421321300206164540821986138099462721214327234457806819925823202851398237118926541234460723597174777907172041523181575194793527456442984630888846385381068621715274531612303165705848974316209831401326306699896632888532682145204083110738032052784669279984003137878996525635126885368435559620598057278951754498694219326972133205286374577983487319388899574634252048213337552584571056619586932031563299451502519194559691231437579991138301656117185508816658756751184338145761060365142858427872190232598107834593970738225147111878311540875777560020664124562293239116606733386480367086953749244898068000217666674827426925968686433731916548717750106343608307376281613984107392410037196754833838054369880310983922140260514297591221159148505938770679068701351029862207502287721123345624421024715163941251258954337788492834236361124473822814504596821452253550035968325337489186278678359443979041598043992124889848660795045011701169092519383155609441705397900600291315024253848282782826223304151370929502192196508374714697845805550615914539506437316401173317807741497557116733034632008408954066541694665746735785483133770133628948904397670025863002540635264006601631712883920305576358989492412827022489373848906764385339931878608019223108328847459816417701264089078551777830131616162049792779670521847212730327970738223860581986744668610994383049960437407323195784473254857416239738852016202384784256163512597161783106850156299135559874758848151014815490937380933394074455700842090155903853444962128368313687375166780513082594599771257467939781491953642874321122421579851584491669362551569370916855252644720786527971466476760328471332985501945689772758983450586004316822658631176606237201721007922216410188299330808409384014213759697185976897042759041500946595252763487628135867117352364964121058854934496645898651826545634382851159137631569519895230262881794959971545221250667461174394884433312659432286710965281109501693028351496524082850120190831078678067061851145740970787563117610746428835593915985421673115153096948758378955979586132649569817205284291038172721213138681565524428109871168862743968021885581515367531218374119972919471325465199144188500672036481975944167950887487934416759598361960010994838744709079104099785974656112459851972157558134628546189728615020774374529539536929655449012953097288963767713353842429715394179547179095580120134210175150931491664699052366350233024087218654727629639065723341455005903913890253699317155917179823065162679744711857951506573868504088229934804445549850597823297898617029498418376255258757455303112991914341109413088238114443068843062655305601658801408561023324210300218460588586954418502977463085858496130037238190325162225570729975710727306066072916922978033647048840958711228045188511908718588299514331534128549297173849768523136276076868494780364948299904475715771141080958058141208956059471668626290036145602625334863284986816039463372436667112964460292915746181117789169695839947080954788863503281129626899231110099889317815313946681882028368363373822281414974006917942192888817139116283910295684918233358930813360131488748366464224381776081007739183393749346933644748150564933649323157235306109385796839902153381449126925350768211098738352197507736653475499431740580563099143218212547336281359488317681489194306530426029773885492974570569448783077945878865062970895499843760181694031056909587141386804846359853684034105948341788438963179956468815791937174656705047441528027712541569401365862097760735632832966564135817028088013546326104892768731829917950379944446328158595181380144716817284996793061814177131912099236282922612543236071226270324572637946863533391758737446552006008819975294017572421299723542069630427857950608911113416534893431149175314953530067419744979017235181671568754163484949491289001739377451431928382431183263265079530371177806185851153508809998200482761808307209649636476943066172549186143700971387567940218696710148540307471561091358933165600167252126542502898612259306484105898847129649230941215144563947889999327145875969555737090855150648002321476443037232466147111552578583071024936898814562568786834745518893385181791667579054210421036349316257870476543126790661216644142285017446278477132740595579600648343288827864837043456066966456899746910373987712891593313271266247505582258634928427718355831641593667712218537642376222104779338956378722902509543014182257180331300148113377736941508488867501893156994849838936052666818012783912005801431596441910546663236810148207799356523056490420711364192200177189107935243234322761787712568251126481332974354926568682748715986654943041648468220593921673359485057849622807932422649812705271398407720995707236227009245067665680069149966555737866411877079767754867028786431817941521796178310655030287157272282250812017060713380339641841211253856248920130010782462165136989511064611133562443838185366273563783436921279354709230119655914915800561707258518503167289370411936374780625824298250726464801821523430268081486978164824349353456855843696378384153838051184406043696871666416514036129729992912630842812149152469877429332305214999981829046119471676727503742221367186614654042534463141660649871499001000660041544868437352208483059495953182872280520828676300361091734508632133033647289584176588755345227938480297724485711815574893561311524926772006362198369980664159549388683836411891430443767715498026544959061738265591178545999378510861446014967645550103653971251138583505085112442517772923814396233043724036032603181442991365750246012787514117944901305803452199992701148071712847770301254994886841867572975189214295652512486943983729047410363121899124217339550688778643130750024823361832738729697376598820053895902935486054979802320400472236873557411858132734337978931582039412878989728973298812553514507641535360519462112217000676321611195841029252568536561813138784086477147099724553013170761712163186600291464501378587854802096244703771373587720086738054108140042311418525803293267396324596914044834665722042880679280616029884043400536534009706581694636096660911110968789751801325224478246957913251892122653056085866541115373584912790254654369020869419871125588453729063224423222287139122012248769976837147645598526739225904997885514250047585260297929306159913444898341973583316070107516452301310796620382579278533125161760789984630103493496981494261055367836366022561213767081421091373531780682420175737470287189310207606953355721704357535177461573524838432101571399813798596607129664438314791296359275429627129436142685922138993054980645399144588692472767598544271527788443836760149912897358259961869729756588978741082189422337344547375227693199222635973520722998387368484349176841191020246627479579564349615012657433845758638834735832242535328142047826934473129971189346354502994681747128179298167439644524956655532311649920677163664580318205849626132234652606175413532444702007661807418914040158148560001030119994109595492321434406067634769713089513389171050503856336503545166431774489640061738861761193622676890576955693918707703942304940038440622614449572516631017080642923345170422426679607075404028551182398361531383751432493056398381877995594942545196756559181968690885283434886050828529642437578712929439366177362830136595872723080969468398938676366226456791132977469812675226595621009318322081754694778878755356188335083870248295346078597023609865656376722755704495258739871812593441903785275571333409842450127258596692434317689018966145404453679047136294238156127656824247864736176671770647002431119711090007474065945650315375044177982192306323700872039212085499569681061379189029961178936752146022386905665481382858280449537530160921422195940638787074787991194920898374091788534417523064715030278397979864517336625329511775105559014160459873338186887977858817291976604516353353556047648420520888811722831990044504284486852338334530105533929637308039738230604714104525470094899407601215247602819963846343554852932377161410869591950786873276075400085220065031871239272857835807010762542769655355964789450166013816295177908531139811092831583216931563867459747449584385282701658246192092219529134323496779345585613140207765996142546463288677356891785576835169608392864188830094883324700447958316931533832382377876344426323456301679513671047510469669001217777128065522453689371871451567394733440447280450959433090683667110655953338602938000999949010642769859623260401863733572846679531229683156358145420890540651226419162015504500430562136991850941034609601030543816694795964585804425194905110733387679946734471718615647723811737035654917628707589456035519195603962301157866323750234725054461073979402475184415558178087962822231972692984516683306919505079993357259165675557294585962182052650473353712351623662770479333289322136141858785972771685682725303734836891911847197133753088446777943274857148827821608844765700041403499921376794209627560883081509438030705666022764678117533361028187800710219794428777313146387857817205661409023041499923248268982477222109852189758140879763486146763606368674611966620347304608917277240045953051376938375381543486981101990651706961774052218247422657652138152740612699012706880875386408669901461740890540981877671880076124151967064152117653084325544261017536348281196837493395825742541244634247233586360777980960199745187758845459645895956779558869098404768259253477849930457883128541747079059795909431627722327844578918694214929451540174214623240300841907975296782445969183509474202123617940309048634960534054931299919496087957952586977170236680033862505764938088740994009589948109397983231108838769236490221499111120870639202892490698435333152727991330986335454324971441378059132240814960156485679843966464780280409057580889190254236606774500413415794312112501275232250148067232979652230488493751166084976116412777395311302041566848265531411348993243747890268935173904043294851610659785832253168204202834993641595980197343889883020994152152288611175126686173051956249367180053845637855129171848417841594797435580617856680758491080185805695567990185198397660693358224779136504562705766735170961550493338390452612404395517449136885115987454340932040102218982707539212403241042424451570052968378815749468441508011138612561164102477190903050040240662278945607061512108266146098662040425010583978098192019726759010749924884966139441184159734610382401178556739080566483321039073867083298691078093495828888707110651559651222542929154212923108071159723275797510859911398076844732639426419452063138217862260999160086752446265457028969067192282283045169111363652774517975842147102219099906257373383472726498678244401048998507631630668050267115944636293525120269424810854530602810627264236538250773340575475701704367039596467715959261029438313074897245505729085688496091346323165819468660587092144653716755655531962091865952628448253731353698162517351930115341581171353292035873164168839107994000677266031617527582917398395852606454113318985505747847121053505795649095931672167565624818782002769963734155880000867852567422461511406015760115910256449002264980039498403358091309140197877843650167960167465370287466062584346329708303725980494653589318912163976013193079476972058034710553111117215859219066231028099212084069283091906017370764654655683413207556315315006453462321007133584907633048328153458698497332599801187479664273140279381289961720524540674695271948079930396730194274036466594154400092799908634806622334906695224044652158992864203435098858422692019340575496840904812955522654754650713532842543496616084954788090727649930252702815067862810825243222979985391759845188868387004477101866772159439708514664612871148749531862180941719676843144666435175837688436786081446319641912566574047718699160915550910878919431253671945651261878486910876729910565595155159739659034383628124629118117760949411880105946336671039049777312004243578115790429823045072038322781246413671297959415082918378213212876890545963586369344879749784841123274921331663162812456388238288715648447883142417650147980187858215768793063001153788998014623690135803753306246148576074932567807682651045738059018831237617271889933790487113395588485234240255002352200613574914318259142479829367775490496399350755839668967578364316618369307625603528602940662803255416535431518013714821941772672244005268401996533334184004345525296592918502940131600651124395297874364222806977720437363717873457948420238745151249157913139411148608416429347958793681868609689684640858334131017858142710955416293375915178392341303110543328703526599993904966822112768158316511246866451167351378214345336650598328347443536290312393672084593164394941881138607974670134709640378534907149089842317891739783650654751982883367395714360000003439863363212091718954899055748693397700245632475954504411422582410783866837655467400137324322809113692670682805397549111166171102397437749479335174036135005397581475520834285772800986189401984375446435081498218360112577632447389452051636938585136484259964518361856989088721789764694721246807900330925083496645841656554261294195108847197209106605105540933731954888406444080280579549008076040034154662137669606444293774985897353625591959618552448187940317374508256072895120945456562159540405425814886929842786582357673195799285293120866275922366115137445767916063621675267440451221051052090834707443986137829082352772895849625656881972792768694795806100573787084121444815034797422312103295359297822377134077549545477791813823542607184617108389097825964406170543546968567030745411634244134486308676327949177682923093183221341455482591367202823284396549001805653203960795517074496039006696990334199278212696767771835209083959545341866777944872740383733381985235884202840150981579594685874537989503257362809837592216229258598599123843993575573285028613155970362934249814178056461615863415338635077223269996508860870999964899373049307170967888740149746147542880387421250689212155876692242387434701120990859082164073576380817386959755176083877600277517253037133445654852635661720197563001580049790223419586738061442401502436288957503206533690825756785507020555105572381878574650371086308158185862815883054564662297694803970618265491385181326737485227188267917919091354407852685476254126683398240534022469989966652573155637645862251862823092085424412805997628505488913098331761884983352975136073772030571342739638126588567405013841074788943393996603591853934198416322617654857376671943132840050626295140357877264680649549355746326408186979718630218760025813995719923601345374229758918285167511358171472625828596940798518571870075823122317068134867930884899275181661399609753105295773584618525865211893339375771859916335112163441037910451845019023066893064178977808158101360449495409665363660370075881004450265734935127707426742578608784898185628869980851665713320835842613381142623855420315774246613108873106318111989880289722849790551075148403702290580483052731884959994156606537314021296702220821915862905952604040620011815269664910068587592655660567562963361434230232810747488395040380984981860056164646099819257616235478710913832967563761506732550860683433720438748186791668975746563456020002562889601191100980453350423842063824039434163502977688802779835087481178298349417211674919425601608685332435385951152061809031241698182079314615062073826097180458265687043623935757495737332781578904386011378078508110273049446611821957450170106059384336519458628360682108585130499820420578458577175933849015564447305834515291412561679970569657426139901681932056241927977282026714297258700193234337873153939403115411184101414292741703537542003698760608765500109345299007034032401334806388514095769557147190364152027721127070187421548123931953220997506553022646844227700020589045922742423904937051507367764629844971682121994198274794049092601715727439368569721862936007387077810797440975556627807371228030350048829843919546433753355787895064018998685060281902452191177018634505171087023903398550540704454189088472042376499749035038518949505897971286631644699407490959473411581934618336692169573605081585080837952036335619947691937965065016808710250735070825260046821242820434367245824478859256555487861614478717581068572356895150707602217433511627331709472765932413249132702425519391509083601346239612335001086614623850633127072987745618984384288764099836164964775714638573247333226653894523588365972955159905187411779288608760239306160016168434070611663449248395156319152882728822831375458678269830696691220130954815935450754923554167766876455212545681242936427474153815692219503331560151614492247512488957534835926226263545406704767033866410025277276800886383266629488582740369655329362236090572479794734434077704284318507901973469071141230364111729224929307731939309795452877412451183953480382210373644697046967493042810911797232448615413264031578430955396671061468083815548947146733652483679138566431084747848676243012018489329109615281108087617422779131629345494425395422727309645057976122885347393189600810965202090151104579377602529543130188938184010247010134929317443562883578609861545691161669857388024973756940558138630581099823372565164920155443216861690537054630176154809626620800633059320775897175589925862195462096455464624399535391743228225433267174308492508396461328929584567927365409119947616225155964704061297047759818551878441419948614013153859322060745185909608884280218943358691959604936409651570327527570641500776261323783648149005245481413195989296398441371781402764122087644989688629798910870164270169014007825748311598976330612951195680427485317886333041169767175063822135213839779138443325644288490872919067009802496281560626258636942322658490628628035057282983101266919109637258378149363774960594515216932644945188292639525772348420077356021656909077097264985642831778694777804964343991762549216500608626285329471055602670413384500507827390640287529864161287496473708235188892189612641279553536442286955430551308700009878557534223100547153412810957024870812654319123261956462149376527526356402127388765103883255007364899937167183280028398832319373301564123277185395654932422977953016534830128490677845037490891749347389015649588574802194996722621185874361039774946338633057887487405540005440439344888192044102134790034598411927024921557026873700970995205391930979319495883265922171508324621942300185974396706491149559411733728199869021311629886680267446443489233020607003821262841723679627307191405008084085703978151998148822390059948911946474438682533745889962375133378280532928272016815977970066488394482446332210928320504045983008943565954267256879714918703447338237767914829203283196838105907715727191903042365315650957464549643425328069510396558733549803850995143463506175361480050195045201350200180281506933241918267855737764414097080945745624854867704904368368717590918057269794010465019484853146726642978667687697789291431128505043098192949736165944259471754765135205245072597538577958372797702972231435199958499522344049394502115428867244188717409524554771867484911475031801773304689909317974472957035192387686405544278134169807249382219749124257510162187439772902147704638010731470653154201300583810458905006764557332998149945854655105526374914354195867992595981412218735238407957416123372264063860431988936249867649693592569592128495906254446474331759999685163660305216426770428154681777589339252115538590526823311608302751194384823861552852465010329467297198112105314125898165100120742688143577590825227466863206188376830450921784582526239594189673003640808624233657620979111641766331328852352062487922978959456450333733139422384778582717195412347860434376165241568717943562570215636666680088531006728947033079540804583324192188488870712275670333173939262509073556164513677064199539111948881240659821685787131385056850623094155206877987539740658484250135205615103489821873770245063583314243624807432542464195984647411575625441010389671576677263196442524931941806472423789334668561083789808830313571333157729435664956078125304917594015895146954965223118559669048559467607968190167266634650186182955669893965019614544401768162810604465068448139561667220729261210164692339016793399632833013163850830967942792934551268435760356901970523138364640961311774904600772840862214747547653221505518116489887879087780918009050706040061220010051271575991225725282523378026809030528461581739558198122397010092017202251606352922464781615533532275453264543087093320924631855976580561717446840450048285353396546862678852330044967795580761661801833668792312510460809773895565488962815089519622093675058841609752282328250433712970186608193748968699961301486924694482420723632912367052542145464162968910442981633373266871675946715392611950649224725627254543274193495995569590243279097174392258098103601486364409101491734183079646345064833303404765711827040276868271418084574998493392039317445402616663674646668754385093967129918067471909885312710726724428584870694307099756567949198418996425748884764622030325637751112534060087936904565779272035205921345924272965206683338510673615276261016026647772485083344719891986802656197236420847504962661607797092906844757798251795569758235084371746103310387911789239441630112634077535773520558040066982523191225570519133631407211349723226549151062961739050617857127509403623146700931176133132018631158730886798239298009805089491510788371194099750375473674305745187265414016446924576792185753680363289139664155342066705623272936001177781498886100830877849571709880858667023104043242526785955562077310543072298032125941107957349146684680220501816192150766649106862033378713826058987655210423668198670177861672671972374156917880001690656659046965316154923604061891820982414006103779407166342002735828911994182647812782659666207030384795881442790246669264032799404016800137293477301530941805070587421153284642203006550763966756168318897005152026656649929417382840327305940740147117478464839241225676523593418554066440983706083636457657081801664285044258224551650808864421212113914352453935225522162483791737330329812349528984098613273709957407786789349311975204237925022851375880436791854547836416773151821457226504640800104202100410766027807729152555503218182387221708112766208665317651926458452495269685376314437998340336947124447247796973890514941120010934140073794061859447165516612674930799374705772930521750426383798367668159183589049652163726492960837147204067428996276720315410211504333742057182854090136325721437592054640471894328548696883599785122262130812989581571391597464534806099601555877223193450760315411663112963843719400333736013305526352571490454327925190794007111504785378036370897340146753465517470747096935814912797188187854376797751675927822300312945518595042883902735494672667647506072643698761394806879080593531793001711000214417701504495496412454361656210150919997862972495905809191825255486358703529320142005857057855419217730505342687533799076038746689684283402648733290888881745453047194740939258407362058242849349024756883352446212456101562729065130618520732925434179252299417447855189995098959999877410951464170076989305620163502192692653166599093238118295411937545448509428621839424186218067457128099385258842631930670182098008050900019819621758458932516877698594110522845465835679362969619219080897536813210484518784516230623911878024604050824909336069998094776253792973597037759066145994638578378211017122446355845171941670344732162722443265914858595797823752976323442911242311368603724514438765801271594060878788638511089680883165505046309006148832545452819908256238805872042843941834687865142541377686054291079721004271658 -------------------------------------------------------------------------------- /examples/trees/avl-tree-test.go: -------------------------------------------------------------------------------- 1 | // source: http://rosettacode.org/wiki/AVL_tree#Go 2 | // adapted to our library 3 | 4 | package main 5 | 6 | import ( 7 | "encoding/json" 8 | "fmt" 9 | "github.com/gophergala/go-algos/trees" 10 | "log" 11 | ) 12 | 13 | type intKey int 14 | 15 | // satisfy trees.Key 16 | func (k intKey) Less(k2 trees.Key) bool { return k < k2.(intKey) } 17 | func (k intKey) Eq(k2 trees.Key) bool { return k == k2.(intKey) } 18 | 19 | // use json for cheap tree visualization 20 | func dump(tree *trees.Node) { 21 | b, err := json.MarshalIndent(tree, "", " ") 22 | if err != nil { 23 | log.Fatal(err) 24 | } 25 | fmt.Println(string(b)) 26 | } 27 | 28 | func main() { 29 | var tree *trees.Node 30 | fmt.Println("Empty tree:") 31 | dump(tree) 32 | 33 | fmt.Println("\nInsert test:") 34 | trees.Insert(&tree, intKey(3)) 35 | trees.Insert(&tree, intKey(1)) 36 | trees.Insert(&tree, intKey(4)) 37 | trees.Insert(&tree, intKey(1)) 38 | trees.Insert(&tree, intKey(5)) 39 | dump(tree) 40 | 41 | fmt.Println("\nRemove test:") 42 | trees.Remove(&tree, intKey(3)) 43 | trees.Remove(&tree, intKey(1)) 44 | dump(tree) 45 | } 46 | 47 | -------------------------------------------------------------------------------- /search/astar.go: -------------------------------------------------------------------------------- 1 | // source: https://github.com/xarg/gopathfinding/blob/master/astar.go 2 | 3 | //pathfinding package implements pathfinding algorithms such as Dijkstra and A* 4 | package search 5 | 6 | import ( 7 | "fmt" 8 | ) 9 | 10 | //Defining possible graph elements 11 | const ( 12 | UNKNOWN int = iota - 1 13 | LAND 14 | WALL 15 | START 16 | STOP 17 | ) 18 | 19 | type MapData [][]int 20 | 21 | //Return a new MapData by value given some dimensions 22 | func NewMapData(rows, cols int) *MapData { 23 | result := make(MapData, rows) 24 | for i := 0; i < rows; i++ { 25 | result[i] = make([]int, cols) 26 | } 27 | return &result 28 | } 29 | 30 | //A node is just a set of x, y coordinates with a parent node and a 31 | //heuristic value H 32 | type Node struct { 33 | x, y int //Using int for efficiency 34 | parent *Node 35 | H int //Heuristic (aproximate distance) 36 | cost int //Path cost for this node 37 | } 38 | 39 | //Create a new node 40 | func NewNode(x, y int) *Node { 41 | node := &Node{ 42 | x: x, 43 | y: y, 44 | parent: nil, 45 | H: 0, 46 | cost: 0, 47 | } 48 | return node 49 | } 50 | 51 | //Return string representation of the node 52 | func (self *Node) String() string { 53 | return fmt.Sprintf("", self.x, self.y, &self) 54 | } 55 | 56 | //Start, end nodes and a slice of nodes 57 | type Graph struct { 58 | start, stop *Node 59 | nodes []*Node 60 | data *MapData 61 | } 62 | 63 | //Return a Graph from a map of coordinates (those that are passible) 64 | func NewGraph(map_data *MapData) *Graph { 65 | var start, stop *Node 66 | var nodes []*Node 67 | for i, row := range *map_data { 68 | for j, _type := range row { 69 | if _type == START || _type == STOP { 70 | node := NewNode(i, j) 71 | nodes = append(nodes, node) 72 | if _type == START { 73 | start = node 74 | } 75 | if _type == STOP { 76 | stop = node 77 | } 78 | } 79 | } 80 | } 81 | g := &Graph{ 82 | nodes: nodes, 83 | start: start, 84 | stop: stop, 85 | data: map_data, 86 | } 87 | return g 88 | } 89 | 90 | //Get *Node based on x, y coordinates. 91 | func (self *Graph) Node(x, y int) *Node { 92 | //Check if node is not already in the graph and append that node 93 | for _, n := range self.nodes { 94 | if n.x == x && n.y == y { 95 | return n 96 | } 97 | } 98 | map_data := *self.data 99 | if map_data[x][y] == LAND || map_data[x][y] == STOP { 100 | //Create a new node and add it to the graph 101 | n := NewNode(x, y) 102 | self.nodes = append(self.nodes, n) 103 | return n 104 | } 105 | return nil 106 | } 107 | 108 | //Get the nodes near some node 109 | func (self *Graph) adjacentNodes(node *Node) []*Node { 110 | var result []*Node 111 | map_data := *self.data 112 | rows := len(map_data) 113 | cols := len(map_data[0]) 114 | 115 | //If the coordinates are passable then create a new node and add it 116 | if node.x <= rows && node.y+1 < cols { 117 | if new_node := self.Node(node.x, node.y+1); new_node != nil { 118 | result = append(result, new_node) 119 | } 120 | } 121 | if node.x <= rows && node.y-1 >= 0 { 122 | new_node := self.Node(node.x, node.y-1) 123 | if new_node != nil { 124 | result = append(result, new_node) 125 | } 126 | } 127 | if node.y <= cols && node.x+1 < rows { 128 | new_node := self.Node(node.x+1, node.y) 129 | if new_node != nil { 130 | result = append(result, new_node) 131 | } 132 | } 133 | if node.y <= cols && node.x-1 >= 0 { 134 | new_node := self.Node(node.x-1, node.y) 135 | if new_node != nil { 136 | result = append(result, new_node) 137 | } 138 | } 139 | return result 140 | } 141 | 142 | func abs(x int) int { 143 | if x < 0 { 144 | return -x 145 | } 146 | return x 147 | } 148 | 149 | func removeNode(nodes []*Node, node *Node) []*Node { 150 | ith := -1 151 | for i, n := range nodes { 152 | if n == node { 153 | ith = i 154 | break 155 | } 156 | } 157 | if ith != -1 { 158 | copy(nodes[ith:], nodes[ith+1:]) 159 | nodes = nodes[:len(nodes)-1] 160 | } 161 | return nodes 162 | } 163 | 164 | func hasNode(nodes []*Node, node *Node) bool { 165 | for _, n := range nodes { 166 | if n == node { 167 | return true 168 | } 169 | } 170 | return false 171 | } 172 | 173 | //Return the node with the minimum H 174 | func minH(nodes []*Node) *Node { 175 | if len(nodes) == 0 { 176 | return nil 177 | } 178 | result_node := nodes[0] 179 | minH := result_node.H 180 | for _, node := range nodes { 181 | if node.H < minH { 182 | minH = node.H 183 | result_node = node 184 | } 185 | } 186 | return result_node 187 | } 188 | 189 | func retracePath(current_node *Node) []*Node { 190 | var path []*Node 191 | path = append(path, current_node) 192 | for current_node.parent != nil { 193 | path = append(path, current_node.parent) 194 | current_node = current_node.parent 195 | } 196 | //Reverse path 197 | for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 { 198 | path[i], path[j] = path[j], path[i] 199 | } 200 | return path 201 | } 202 | 203 | // In our particular case: Manhatan distance 204 | func Heuristic(graph *Graph, tile *Node) int { 205 | return abs(graph.stop.x-tile.x) + abs(graph.stop.y-tile.y) 206 | } 207 | 208 | //A* search algorithm. See http://en.wikipedia.org/wiki/A*_search_algorithm 209 | func Astar(graph *Graph) []*Node { 210 | var path, openSet, closedSet []*Node 211 | 212 | openSet = append(openSet, graph.start) 213 | for len(openSet) != 0 { 214 | //Get the node with the min H 215 | current := minH(openSet) 216 | if current.parent != nil { 217 | current.cost = current.parent.cost + 1 218 | } 219 | if current == graph.stop { 220 | return retracePath(current) 221 | } 222 | openSet = removeNode(openSet, current) 223 | closedSet = append(closedSet, current) 224 | for _, tile := range graph.adjacentNodes(current) { 225 | if tile != nil && graph.stop != nil && !hasNode(closedSet, tile) { 226 | tile.H = Heuristic(graph, tile) + current.cost 227 | if !hasNode(openSet, tile) { 228 | openSet = append(openSet, tile) 229 | } 230 | tile.parent = current 231 | } 232 | } 233 | } 234 | return path 235 | } 236 | -------------------------------------------------------------------------------- /search/bfs.go: -------------------------------------------------------------------------------- 1 | // source: https://github.com/adlawson/search-algorithms/blob/master/golang/bfs.go 2 | 3 | package search 4 | 5 | func dfs(node int, nodes map[int][]int, fn func (int)) { 6 | dfs_recur(node, map[int]bool{}, fn) 7 | } 8 | 9 | func dfs_recur(node int, v map[int]bool, fn func (int)) { 10 | v[node] = true 11 | fn(node) 12 | for _, n := range nodes[node] { 13 | if _, ok := v[n]; !ok { 14 | dfs_recur(n, v, fn) 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /search/binary-search.go: -------------------------------------------------------------------------------- 1 | package search 2 | 3 | // source: http://rosettacode.org/wiki/Binary_search#Go 4 | 5 | // iterative version 6 | func binarySearch(a []float64, value float64) int { 7 | low := 0 8 | high := len(a) - 1 9 | for low <= high { 10 | mid := (low + high) / 2 11 | if a[mid] > value { 12 | high = mid - 1 13 | } else if a[mid] < value { 14 | low = mid + 1 15 | } else { 16 | return mid 17 | } 18 | } 19 | return -1 20 | } 21 | -------------------------------------------------------------------------------- /search/dfs.go: -------------------------------------------------------------------------------- 1 | // source: https://github.com/adlawson/search-algorithms/blob/master/golang/dfs.go 2 | 3 | package search 4 | 5 | func dfs(node int, nodes map[int][]int, fn func (int)) { 6 | dfs_recur(node, map[int]bool{}, fn) 7 | } 8 | 9 | func dfs_recur(node int, v map[int]bool, fn func (int)) { 10 | v[node] = true 11 | fn(node) 12 | for _, n := range nodes[node] { 13 | if _, ok := v[n]; !ok { 14 | dfs_recur(n, v, fn) 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /search/pagerank.go: -------------------------------------------------------------------------------- 1 | package search 2 | 3 | // source: https://github.com/dcadenas/pagerank/blob/master/pagerank.go 4 | 5 | import "math" 6 | 7 | type Interface interface { 8 | Rank(followingProb, tolerance float64, resultFunc func(label int, rank float64)) 9 | Link(from, to int) 10 | } 11 | 12 | type pageRank struct { 13 | inLinks [][]int 14 | numberOutLinks []int 15 | currentAvailableIndex int 16 | keyToIndex map[int]int 17 | indexToKey map[int]int 18 | } 19 | 20 | func New() *pageRank { 21 | pr := new(pageRank) 22 | pr.Clear() 23 | return pr 24 | } 25 | 26 | func (pr *pageRank) keyAsArrayIndex(key int) int { 27 | index, ok := pr.keyToIndex[key] 28 | 29 | if !ok { 30 | pr.currentAvailableIndex++ 31 | index = pr.currentAvailableIndex 32 | pr.keyToIndex[key] = index 33 | pr.indexToKey[index] = key 34 | } 35 | 36 | return index 37 | } 38 | 39 | func (pr *pageRank) updateInLinks(fromAsIndex, toAsIndex int) { 40 | missingSlots := len(pr.keyToIndex) - len(pr.inLinks) 41 | 42 | if missingSlots > 0 { 43 | pr.inLinks = append(pr.inLinks, make([][]int, missingSlots)...) 44 | } 45 | 46 | pr.inLinks[toAsIndex] = append(pr.inLinks[toAsIndex], fromAsIndex) 47 | } 48 | 49 | func (pr *pageRank) updateNumberOutLinks(fromAsIndex int) { 50 | missingSlots := len(pr.keyToIndex) - len(pr.numberOutLinks) 51 | 52 | if missingSlots > 0 { 53 | pr.numberOutLinks = append(pr.numberOutLinks, make([]int, missingSlots)...) 54 | } 55 | 56 | pr.numberOutLinks[fromAsIndex] += 1 57 | } 58 | 59 | func (pr *pageRank) linkWithIndices(fromAsIndex, toAsIndex int) { 60 | pr.updateInLinks(fromAsIndex, toAsIndex) 61 | pr.updateNumberOutLinks(fromAsIndex) 62 | } 63 | 64 | func (pr *pageRank) Link(from, to int) { 65 | fromAsIndex := pr.keyAsArrayIndex(from) 66 | toAsIndex := pr.keyAsArrayIndex(to) 67 | 68 | pr.linkWithIndices(fromAsIndex, toAsIndex) 69 | } 70 | 71 | func (pr *pageRank) calculateDanglingNodes() []int { 72 | danglingNodes := make([]int, 0, len(pr.numberOutLinks)) 73 | 74 | for i, numberOutLinksForI := range pr.numberOutLinks { 75 | if numberOutLinksForI == 0 { 76 | danglingNodes = append(danglingNodes, i) 77 | } 78 | } 79 | 80 | return danglingNodes 81 | } 82 | 83 | func (pr *pageRank) step(followingProb, tOverSize float64, p []float64, danglingNodes []int) []float64 { 84 | innerProduct := 0.0 85 | 86 | for _, danglingNode := range danglingNodes { 87 | innerProduct += p[danglingNode] 88 | } 89 | 90 | innerProductOverSize := innerProduct / float64(len(p)) 91 | vsum := 0.0 92 | v := make([]float64, len(p)) 93 | 94 | for i, inLinksForI := range pr.inLinks { 95 | ksum := 0.0 96 | 97 | for _, index := range inLinksForI { 98 | ksum += p[index] / float64(pr.numberOutLinks[index]) 99 | } 100 | 101 | v[i] = followingProb*(ksum+innerProductOverSize) + tOverSize 102 | vsum += v[i] 103 | } 104 | 105 | inverseOfSum := 1.0 / vsum 106 | 107 | for i := range v { 108 | v[i] *= inverseOfSum 109 | } 110 | 111 | return v 112 | } 113 | 114 | func calculateChange(p, new_p []float64) float64 { 115 | acc := 0.0 116 | 117 | for i, pForI := range p { 118 | acc += math.Abs(pForI - new_p[i]) 119 | } 120 | 121 | return acc 122 | } 123 | 124 | func (pr *pageRank) Rank(followingProb, tolerance float64, resultFunc func(label int, rank float64)) { 125 | size := len(pr.keyToIndex) 126 | inverseOfSize := 1.0 / float64(size) 127 | tOverSize := (1.0 - followingProb) / float64(size) 128 | danglingNodes := pr.calculateDanglingNodes() 129 | 130 | p := make([]float64, size) 131 | for i := range p { 132 | p[i] = inverseOfSize 133 | } 134 | 135 | change := 2.0 136 | 137 | for change > tolerance { 138 | new_p := pr.step(followingProb, tOverSize, p, danglingNodes) 139 | change = calculateChange(p, new_p) 140 | p = new_p 141 | } 142 | 143 | for i, pForI := range p { 144 | resultFunc(pr.indexToKey[i], pForI) 145 | } 146 | } 147 | 148 | func (pr *pageRank) Clear() { 149 | pr.inLinks = [][]int{} 150 | pr.numberOutLinks = []int{} 151 | pr.currentAvailableIndex = -1 152 | pr.keyToIndex = make(map[int]int) 153 | pr.indexToKey = make(map[int]int) 154 | } -------------------------------------------------------------------------------- /sort/bubblesort.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | import { 4 | "fmt" 5 | } 6 | 7 | /* 8 | * Referenced from: http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort#Go 9 | */ 10 | func bubblesort(a []int) { 11 | for itemCount := len(a) - 1; ; itemCount-- { 12 | hasChanged := false 13 | for index := 0; index < itemCount; index++ { 14 | if a[index] > a[index+1] { 15 | a[index], a[index+1] = a[index+1], a[index] 16 | hasChanged = true 17 | } 18 | } 19 | if !hasChanged { 20 | break 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /sort/countsort.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | import { 4 | "fmt" 5 | } 6 | /* 7 | * Referenced from: http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort#Go 8 | */ 9 | func countingSort(a []int, aMin, aMax int) { 10 | defer func() { 11 | if x := recover(); x != nil { 12 | // one error we'll handle and print a little nicer message 13 | if _, ok := x.(runtime.Error); ok && 14 | strings.HasSuffix(x.(error).Error(), "index out of range") { 15 | fmt.Printf("data value out of range (%d..%d)\n", aMin, aMax) 16 | return 17 | } 18 | // anything else, we re-panic 19 | panic(x) 20 | } 21 | }() 22 | 23 | count := make([]int, aMax-aMin+1) 24 | for _, x := range a { 25 | count[x-aMin]++ 26 | } 27 | z := 0 28 | // optimization over task pseudocode: variable c is used instead of 29 | // count[i-min]. This saves some unneccessary calculations. 30 | for i, c := range count { 31 | for ; c > 0; c-- { 32 | a[z] = i + aMin 33 | z++ 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /sort/heapsort.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | import ( 4 | "sort" 5 | "container/heap" 6 | "fmt" 7 | ) 8 | 9 | /* 10 | * Referenced from: http://rosettacode.org/wiki/Sorting_algorithms/Heapsort#Go 11 | */ 12 | 13 | type HeapHelper struct { 14 | container sort.Interface 15 | length int 16 | } 17 | 18 | func (self HeapHelper) Len() int { return self.length } 19 | // We want a max-heap, hence reverse the comparison 20 | func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) } 21 | func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) } 22 | // this should not be called 23 | func (self *HeapHelper) Push(x interface{}) { panic("impossible") } 24 | func (self *HeapHelper) Pop() interface{} { 25 | self.length-- 26 | return nil // return value not used 27 | } 28 | 29 | func heapSort(a sort.Interface) { 30 | helper := HeapHelper{ a, a.Len() } 31 | heap.Init(&helper) 32 | for helper.length > 0 { 33 | heap.Pop(&helper) 34 | } 35 | } 36 | 37 | /* Example: 38 | * func main() { 39 | * a := []int{170, 45, 75, -90, -802, 24, 2, 66} 40 | * fmt.Println("before:", a) 41 | * heapSort(sort.IntSlice(a)) 42 | * fmt.Println("after: ", a) 43 | * } 44 | * 45 | */ -------------------------------------------------------------------------------- /sort/insertionsort.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | import { 4 | "fmt" 5 | } 6 | /* 7 | * Referenced from: http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#Go 8 | */ 9 | func insertionSort(a []int) { 10 | for i := 1; i < len(a); i++ { 11 | value := a[i] 12 | j := i - 1 13 | for j >= 0 && a[j] > value { 14 | a[j+1] = a[j] 15 | j = j - 1 16 | } 17 | a[j+1] = value 18 | } 19 | } -------------------------------------------------------------------------------- /sort/mergesort.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | import { 4 | "fmt" 5 | } 6 | /* 7 | * Referenced from: http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort#Go 8 | */ 9 | func mergeSort(a []int) { 10 | if len(a) < 2 { 11 | return 12 | } 13 | mid := len(a) / 2 14 | mergeSort(a[:mid]) 15 | mergeSort(a[mid:]) 16 | if a[mid-1] <= a[mid] { 17 | return 18 | } 19 | // merge step, with the copy-half optimization 20 | copy(s, a[:mid]) 21 | l, r := 0, mid 22 | for i := 0; ; i++ { 23 | if s[l] <= a[r] { 24 | a[i] = s[l] 25 | l++ 26 | if l == mid { 27 | break 28 | } 29 | } else { 30 | a[i] = a[r] 31 | r++ 32 | if r == len(a) { 33 | copy(a[i+1:], s[l:mid]) 34 | break 35 | } 36 | } 37 | } 38 | return 39 | } -------------------------------------------------------------------------------- /sort/quicksort.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | import { 4 | "fmt" 5 | } 6 | /* 7 | * Referenced from: http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Go 8 | */ 9 | func quicksort(a []int) { 10 | var pex func(int, int) 11 | pex = func(lower, upper int) { 12 | for { 13 | switch upper - lower { 14 | case -1, 0: // 0 or 1 item in segment. nothing to do here! 15 | return 16 | case 1: // 2 items in segment 17 | // < operator respects strict weak order 18 | if a[upper] < a[lower] { 19 | // a quick exchange and we're done. 20 | a[upper], a[lower] = a[lower], a[upper] 21 | } 22 | return 23 | // Hoare suggests optimized sort-3 or sort-4 algorithms here, 24 | // but does not provide an algorithm. 25 | } 26 | 27 | // Hoare stresses picking a bound in a way to avoid worst case 28 | // behavior, but offers no suggestions other than picking a 29 | // random element. A function call to get a random number is 30 | // relatively expensive, so the method used here is to simply 31 | // choose the middle element. This at least avoids worst case 32 | // behavior for the obvious common case of an already sorted list. 33 | bx := (upper + lower) / 2 34 | b := a[bx] // b = Hoare's "bound" (aka "pivot") 35 | lp := lower // lp = Hoare's "lower pointer" 36 | up := upper // up = Hoare's "upper pointer" 37 | outer: 38 | for { 39 | // use < operator to respect strict weak order 40 | for lp < upper && !(b < a[lp]) { 41 | lp++ 42 | } 43 | for { 44 | if lp > up { 45 | // "pointers crossed!" 46 | break outer 47 | } 48 | // < operator for strict weak order 49 | if a[up] < b { 50 | break // inner 51 | } 52 | up-- 53 | } 54 | // exchange 55 | a[lp], a[up] = a[up], a[lp] 56 | lp++ 57 | up-- 58 | } 59 | // segment boundary is between up and lp, but lp-up might be 60 | // 1 or 2, so just call segment boundary between lp-1 and lp. 61 | if bx < lp { 62 | // bound was in lower segment 63 | if bx < lp-1 { 64 | // exchange bx with lp-1 65 | a[bx], a[lp-1] = a[lp-1], b 66 | } 67 | up = lp - 2 68 | } else { 69 | // bound was in upper segment 70 | if bx > lp { 71 | // exchange 72 | a[bx], a[lp] = a[lp], b 73 | } 74 | up = lp - 1 75 | lp++ 76 | } 77 | // "postpone the larger of the two segments" = recurse on 78 | // the smaller segment, then iterate on the remaining one. 79 | if up-lower < upper-lp { 80 | pex(lower, up) 81 | lower = lp 82 | } else { 83 | pex(lp, upper) 84 | upper = up 85 | } 86 | } 87 | } 88 | pex(0, len(a)-1) 89 | } -------------------------------------------------------------------------------- /sort/selectionsort.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | import { 4 | "fmt" 5 | } 6 | /* 7 | * Referenced from: http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort#Go 8 | */ 9 | func selectionSort(a []int) { 10 | last := len(a) - 1 11 | for i := 0; i < last; i++ { 12 | aMin := a[i] 13 | iMin := i 14 | for j := i + 1; j < len(a); j++ { 15 | if a[j] < aMin { 16 | aMin = a[j] 17 | iMin = j 18 | } 19 | } 20 | a[i], a[iMin] = aMin, a[i] 21 | } 22 | } -------------------------------------------------------------------------------- /sort/shellsort.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | import { 4 | "fmt" 5 | } 6 | /* 7 | * Referenced from: http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort#Go 8 | */ 9 | func shellSort(a []int) { 10 | for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 { 11 | for i := inc; i < len(a); i++ { 12 | j, temp := i, a[i] 13 | for ; j >= inc && a[j-inc] > temp; j -= inc { 14 | a[j] = a[j-inc] 15 | } 16 | a[j] = temp 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /trees/avl-tree.go: -------------------------------------------------------------------------------- 1 | // source: http://rosettacode.org/wiki/AVL_tree#Go 2 | 3 | package trees 4 | 5 | // AVL tree adapted from Julienne Walker's presentation at 6 | // http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx. 7 | // This port uses similar indentifier names. 8 | 9 | // The Key interface must be supported by data stored in the AVL tree. 10 | type Key interface { 11 | Less(Key) bool 12 | Eq(Key) bool 13 | } 14 | 15 | // Node is a node in an AVL tree. 16 | type Node struct { 17 | Data Key // anything comparable with Less and Eq. 18 | Balance int // balance factor 19 | Link [2]*Node // children, indexed by "direction", 0 or 1. 20 | } 21 | 22 | // A little readability function for returning the opposite of a direction, 23 | // where a direction is 0 or 1. Go inlines this. 24 | // Where JW writes !dir, this code has opp(dir). 25 | func opp(dir int) int { 26 | return 1 - dir 27 | } 28 | 29 | // single rotation 30 | func single(root *Node, dir int) *Node { 31 | save := root.Link[opp(dir)] 32 | root.Link[opp(dir)] = save.Link[dir] 33 | save.Link[dir] = root 34 | return save 35 | } 36 | 37 | // double rotation 38 | func double(root *Node, dir int) *Node { 39 | save := root.Link[opp(dir)].Link[dir] 40 | 41 | root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)] 42 | save.Link[opp(dir)] = root.Link[opp(dir)] 43 | root.Link[opp(dir)] = save 44 | 45 | save = root.Link[opp(dir)] 46 | root.Link[opp(dir)] = save.Link[dir] 47 | save.Link[dir] = root 48 | return save 49 | } 50 | 51 | // adjust valance factors after double rotation 52 | func adjustBalance(root *Node, dir, bal int) { 53 | n := root.Link[dir] 54 | nn := n.Link[opp(dir)] 55 | switch nn.Balance { 56 | case 0: 57 | root.Balance = 0 58 | n.Balance = 0 59 | case bal: 60 | root.Balance = -bal 61 | n.Balance = 0 62 | default: 63 | root.Balance = 0 64 | n.Balance = bal 65 | } 66 | nn.Balance = 0 67 | } 68 | 69 | func insertBalance(root *Node, dir int) *Node { 70 | n := root.Link[dir] 71 | bal := 2*dir - 1 72 | if n.Balance == bal { 73 | root.Balance = 0 74 | n.Balance = 0 75 | return single(root, opp(dir)) 76 | } 77 | adjustBalance(root, dir, bal) 78 | return double(root, opp(dir)) 79 | } 80 | 81 | func insertR(root *Node, data Key) (*Node, bool) { 82 | if root == nil { 83 | return &Node{Data: data}, false 84 | } 85 | dir := 0 86 | if root.Data.Less(data) { 87 | dir = 1 88 | } 89 | var done bool 90 | root.Link[dir], done = insertR(root.Link[dir], data) 91 | if done { 92 | return root, true 93 | } 94 | root.Balance += 2*dir - 1 95 | switch root.Balance { 96 | case 0: 97 | return root, true 98 | case 1, -1: 99 | return root, false 100 | } 101 | return insertBalance(root, dir), true 102 | } 103 | 104 | // Insert a node into the AVL tree. 105 | // Data is inserted even if other data with the same key already exists. 106 | func Insert(tree **Node, data Key) { 107 | *tree, _ = insertR(*tree, data) 108 | } 109 | 110 | func removeBalance(root *Node, dir int) (*Node, bool) { 111 | n := root.Link[opp(dir)] 112 | bal := 2*dir - 1 113 | switch n.Balance { 114 | case -bal: 115 | root.Balance = 0 116 | n.Balance = 0 117 | return single(root, dir), false 118 | case bal: 119 | adjustBalance(root, opp(dir), -bal) 120 | return double(root, dir), false 121 | } 122 | root.Balance = -bal 123 | n.Balance = bal 124 | return single(root, dir), true 125 | } 126 | 127 | func removeR(root *Node, data Key) (*Node, bool) { 128 | if root == nil { 129 | return nil, false 130 | } 131 | if root.Data.Eq(data) { 132 | switch { 133 | case root.Link[0] == nil: 134 | return root.Link[1], false 135 | case root.Link[1] == nil: 136 | return root.Link[0], false 137 | } 138 | heir := root.Link[0] 139 | for heir.Link[1] != nil { 140 | heir = heir.Link[1] 141 | } 142 | root.Data = heir.Data 143 | data = heir.Data 144 | } 145 | dir := 0 146 | if root.Data.Less(data) { 147 | dir = 1 148 | } 149 | var done bool 150 | root.Link[dir], done = removeR(root.Link[dir], data) 151 | if done { 152 | return root, true 153 | } 154 | root.Balance += 1 - 2*dir 155 | switch root.Balance { 156 | case 1, -1: 157 | return root, true 158 | case 0: 159 | return root, false 160 | } 161 | return removeBalance(root, dir) 162 | } 163 | 164 | // Remove a single item from an AVL tree. 165 | // If key does not exist, function has no effect. 166 | func Remove(tree **Node, data Key) { 167 | *tree, _ = removeR(*tree, data) 168 | } 169 | -------------------------------------------------------------------------------- /trees/btree.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google 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 | 15 | // Package btree implements in-memory B-Trees of arbitrary degree. 16 | // 17 | // btree implements an in-memory B-Tree for use as an ordered data structure. 18 | // It is not meant for persistent storage solutions. 19 | // 20 | // It has a flatter structure than an equivalent red-black or other binary tree, 21 | // which in some cases yields better memory usage and/or performance. 22 | // See some discussion on the matter here: 23 | // http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html 24 | // Note, though, that this project is in no way related to the C++ B-Tree 25 | // implmentation written about there. 26 | // 27 | // Within this tree, each node contains a slice of items and a (possibly nil) 28 | // slice of children. For basic numeric values or raw structs, this can cause 29 | // efficiency differences when compared to equivalent C++ template code that 30 | // stores values in arrays within the node: 31 | // * Due to the overhead of storing values as interfaces (each 32 | // value needs to be stored as the value itself, then 2 words for the 33 | // interface pointing to that value and its type), resulting in higher 34 | // memory use. 35 | // * Since interfaces can point to values anywhere in memory, values are 36 | // most likely not stored in contiguous blocks, resulting in a higher 37 | // number of cache misses. 38 | // These issues don't tend to matter, though, when working with strings or other 39 | // heap-allocated structures, since C++-equivalent structures also must store 40 | // pointers and also distribute their values across the heap. 41 | // 42 | // This implementation is designed to be a drop-in replacement to gollrb.LLRB 43 | // trees, (http://github.com/petar/gollrb), an excellent and probably the most 44 | // widely used ordered tree implementation in the Go ecosystem currently. 45 | // Its functions, therefore, exactly mirror those of 46 | // llrb.LLRB where possible. Unlike gollrb, though, we currently don't 47 | // support storing multiple equivalent values or backwards iteration. 48 | package trees 49 | 50 | import ( 51 | "fmt" 52 | "io" 53 | "sort" 54 | "strings" 55 | ) 56 | 57 | // Item represents a single object in the tree. 58 | type Item interface { 59 | // Less tests whether the current item is less than the given argument. 60 | // 61 | // This must provide a strict weak ordering. 62 | // If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only 63 | // hold one of either a or b in the tree). 64 | Less(than Item) bool 65 | } 66 | 67 | // ItemIterator allows callers of Ascend* to iterate in-order over portions of 68 | // the tree. When this function returns false, iteration will stop and the 69 | // associated Ascend* function will immediately return. 70 | type ItemIterator func(i Item) bool 71 | 72 | // New creates a new B-Tree with the given degree. 73 | // 74 | // New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items 75 | // and 2-4 children). 76 | func New(degree int) *BTree { 77 | if degree <= 1 { 78 | panic("bad degree") 79 | } 80 | return &BTree{ 81 | degree: degree, 82 | freelist: make([]*node, 0, 32), 83 | } 84 | } 85 | 86 | // items stores items in a node. 87 | type items []Item 88 | 89 | // insertAt inserts a value into the given index, pushing all subsequent values 90 | // forward. 91 | func (s *items) insertAt(index int, item Item) { 92 | *s = append(*s, nil) 93 | if index < len(*s) { 94 | copy((*s)[index+1:], (*s)[index:]) 95 | } 96 | (*s)[index] = item 97 | } 98 | 99 | // removeAt removes a value at a given index, pulling all subsequent values 100 | // back. 101 | func (s *items) removeAt(index int) Item { 102 | item := (*s)[index] 103 | copy((*s)[index:], (*s)[index+1:]) 104 | *s = (*s)[:len(*s)-1] 105 | return item 106 | } 107 | 108 | // pop removes and returns the last element in the list. 109 | func (s *items) pop() (out Item) { 110 | index := len(*s) - 1 111 | out, *s = (*s)[index], (*s)[:index] 112 | return 113 | } 114 | 115 | // find returns the index where the given item should be inserted into this 116 | // list. 'found' is true if the item already exists in the list at the given 117 | // index. 118 | func (s items) find(item Item) (index int, found bool) { 119 | i := sort.Search(len(s), func(i int) bool { 120 | return item.Less(s[i]) 121 | }) 122 | if i > 0 && !s[i-1].Less(item) { 123 | return i - 1, true 124 | } 125 | return i, false 126 | } 127 | 128 | // children stores child nodes in a node. 129 | type children []*node 130 | 131 | // insertAt inserts a value into the given index, pushing all subsequent values 132 | // forward. 133 | func (s *children) insertAt(index int, n *node) { 134 | *s = append(*s, nil) 135 | if index < len(*s) { 136 | copy((*s)[index+1:], (*s)[index:]) 137 | } 138 | (*s)[index] = n 139 | } 140 | 141 | // removeAt removes a value at a given index, pulling all subsequent values 142 | // back. 143 | func (s *children) removeAt(index int) *node { 144 | n := (*s)[index] 145 | copy((*s)[index:], (*s)[index+1:]) 146 | *s = (*s)[:len(*s)-1] 147 | return n 148 | } 149 | 150 | // pop removes and returns the last element in the list. 151 | func (s *children) pop() (out *node) { 152 | index := len(*s) - 1 153 | out, *s = (*s)[index], (*s)[:index] 154 | return 155 | } 156 | 157 | // node is an internal node in a tree. 158 | // 159 | // It must at all times maintain the invariant that either 160 | // * len(children) == 0, len(items) unconstrained 161 | // * len(children) == len(items) + 1 162 | type node struct { 163 | items items 164 | children children 165 | t *BTree 166 | } 167 | 168 | // split splits the given node at the given index. The current node shrinks, 169 | // and this function returns the item that existed at that index and a new node 170 | // containing all items/children after it. 171 | func (n *node) split(i int) (Item, *node) { 172 | item := n.items[i] 173 | next := n.t.newNode() 174 | next.items = append(next.items, n.items[i+1:]...) 175 | n.items = n.items[:i] 176 | if len(n.children) > 0 { 177 | next.children = append(next.children, n.children[i+1:]...) 178 | n.children = n.children[:i+1] 179 | } 180 | return item, next 181 | } 182 | 183 | // maybeSplitChild checks if a child should be split, and if so splits it. 184 | // Returns whether or not a split occurred. 185 | func (n *node) maybeSplitChild(i, maxItems int) bool { 186 | if len(n.children[i].items) < maxItems { 187 | return false 188 | } 189 | first := n.children[i] 190 | item, second := first.split(maxItems / 2) 191 | n.items.insertAt(i, item) 192 | n.children.insertAt(i+1, second) 193 | return true 194 | } 195 | 196 | // insert inserts an item into the subtree rooted at this node, making sure 197 | // no nodes in the subtree exceed maxItems items. Should an equivalent item be 198 | // be found/replaced by insert, it will be returned. 199 | func (n *node) insert(item Item, maxItems int) Item { 200 | i, found := n.items.find(item) 201 | if found { 202 | out := n.items[i] 203 | n.items[i] = item 204 | return out 205 | } 206 | if len(n.children) == 0 { 207 | n.items.insertAt(i, item) 208 | return nil 209 | } 210 | if n.maybeSplitChild(i, maxItems) { 211 | inTree := n.items[i] 212 | switch { 213 | case item.Less(inTree): 214 | // no change, we want first split node 215 | case inTree.Less(item): 216 | i++ // we want second split node 217 | default: 218 | out := n.items[i] 219 | n.items[i] = item 220 | return out 221 | } 222 | } 223 | return n.children[i].insert(item, maxItems) 224 | } 225 | 226 | // get finds the given key in the subtree and returns it. 227 | func (n *node) get(key Item) Item { 228 | i, found := n.items.find(key) 229 | if found { 230 | return n.items[i] 231 | } else if len(n.children) > 0 { 232 | return n.children[i].get(key) 233 | } 234 | return nil 235 | } 236 | 237 | // toRemove details what item to remove in a node.remove call. 238 | type toRemove int 239 | 240 | const ( 241 | removeItem toRemove = iota // removes the given item 242 | removeMin // removes smallest item in the subtree 243 | removeMax // removes largest item in the subtree 244 | ) 245 | 246 | // remove removes an item from the subtree rooted at this node. 247 | func (n *node) remove(item Item, minItems int, typ toRemove) Item { 248 | var i int 249 | var found bool 250 | switch typ { 251 | case removeMax: 252 | if len(n.children) == 0 { 253 | return n.items.pop() 254 | } 255 | i = len(n.items) 256 | case removeMin: 257 | if len(n.children) == 0 { 258 | return n.items.removeAt(0) 259 | } 260 | i = 0 261 | case removeItem: 262 | i, found = n.items.find(item) 263 | if len(n.children) == 0 { 264 | if found { 265 | return n.items.removeAt(i) 266 | } 267 | return nil 268 | } 269 | default: 270 | panic("invalid type") 271 | } 272 | // If we get to here, we have children. 273 | child := n.children[i] 274 | if len(child.items) <= minItems { 275 | return n.growChildAndRemove(i, item, minItems, typ) 276 | } 277 | // Either we had enough items to begin with, or we've done some 278 | // merging/stealing, because we've got enough now and we're ready to return 279 | // stuff. 280 | if found { 281 | // The item exists at index 'i', and the child we've selected can give us a 282 | // predecessor, since if we've gotten here it's got > minItems items in it. 283 | out := n.items[i] 284 | // We use our special-case 'remove' call with typ=maxItem to pull the 285 | // predecessor of item i (the rightmost leaf of our immediate left child) 286 | // and set it into where we pulled the item from. 287 | n.items[i] = child.remove(nil, minItems, removeMax) 288 | return out 289 | } 290 | // Final recursive call. Once we're here, we know that the item isn't in this 291 | // node and that the child is big enough to remove from. 292 | return child.remove(item, minItems, typ) 293 | } 294 | 295 | // growChildAndRemove grows child 'i' to make sure it's possible to remove an 296 | // item from it while keeping it at minItems, then calls remove to actually 297 | // remove it. 298 | // 299 | // Most documentation says we have to do two sets of special casing: 300 | // 1) item is in this node 301 | // 2) item is in child 302 | // In both cases, we need to handle the two subcases: 303 | // A) node has enough values that it can spare one 304 | // B) node doesn't have enough values 305 | // For the latter, we have to check: 306 | // a) left sibling has node to spare 307 | // b) right sibling has node to spare 308 | // c) we must merge 309 | // To simplify our code here, we handle cases #1 and #2 the same: 310 | // If a node doesn't have enough items, we make sure it does (using a,b,c). 311 | // We then simply redo our remove call, and the second time (regardless of 312 | // whether we're in case 1 or 2), we'll have enough items and can guarantee 313 | // that we hit case A. 314 | func (n *node) growChildAndRemove(i int, item Item, minItems int, typ toRemove) Item { 315 | child := n.children[i] 316 | if i > 0 && len(n.children[i-1].items) > minItems { 317 | // Steal from left child 318 | stealFrom := n.children[i-1] 319 | stolenItem := stealFrom.items.pop() 320 | child.items.insertAt(0, n.items[i-1]) 321 | n.items[i-1] = stolenItem 322 | if len(stealFrom.children) > 0 { 323 | child.children.insertAt(0, stealFrom.children.pop()) 324 | } 325 | } else if i < len(n.items) && len(n.children[i+1].items) > minItems { 326 | // steal from right child 327 | stealFrom := n.children[i+1] 328 | stolenItem := stealFrom.items.removeAt(0) 329 | child.items = append(child.items, n.items[i]) 330 | n.items[i] = stolenItem 331 | if len(stealFrom.children) > 0 { 332 | child.children = append(child.children, stealFrom.children.removeAt(0)) 333 | } 334 | } else { 335 | if i >= len(n.items) { 336 | i-- 337 | child = n.children[i] 338 | } 339 | // merge with right child 340 | mergeItem := n.items.removeAt(i) 341 | mergeChild := n.children.removeAt(i + 1) 342 | child.items = append(child.items, mergeItem) 343 | child.items = append(child.items, mergeChild.items...) 344 | child.children = append(child.children, mergeChild.children...) 345 | n.t.freeNode(mergeChild) 346 | } 347 | return n.remove(item, minItems, typ) 348 | } 349 | 350 | // iterate provides a simple method for iterating over elements in the tree. 351 | // It could probably use some work to be extra-efficient (it calls from() a 352 | // little more than it should), but it works pretty well for now. 353 | // 354 | // It requires that 'from' and 'to' both return true for values we should hit 355 | // with the iterator. It should also be the case that 'from' returns true for 356 | // values less than or equal to values 'to' returns true for, and 'to' 357 | // returns true for values greater than or equal to those that 'from' 358 | // does. 359 | func (n *node) iterate(from, to func(Item) bool, iter ItemIterator) bool { 360 | for i, item := range n.items { 361 | if !from(item) { 362 | continue 363 | } 364 | if len(n.children) > 0 && !n.children[i].iterate(from, to, iter) { 365 | return false 366 | } 367 | if !to(item) { 368 | return false 369 | } 370 | if !iter(item) { 371 | return false 372 | } 373 | } 374 | if len(n.children) > 0 { 375 | return n.children[len(n.children)-1].iterate(from, to, iter) 376 | } 377 | return true 378 | } 379 | 380 | // Used for testing/debugging purposes. 381 | func (n *node) print(w io.Writer, level int) { 382 | fmt.Fprintf(w, "%sNODE:%v\n", strings.Repeat(" ", level), n.items) 383 | for _, c := range n.children { 384 | c.print(w, level+1) 385 | } 386 | } 387 | 388 | // BTree is an implementation of a B-Tree. 389 | // 390 | // BTree stores Item instances in an ordered structure, allowing easy insertion, 391 | // removal, and iteration. 392 | // 393 | // Write operations are not safe for concurrent mutation by multiple 394 | // goroutines, but Read operations are. 395 | type BTree struct { 396 | degree int 397 | length int 398 | root *node 399 | freelist []*node 400 | } 401 | 402 | // maxItems returns the max number of items to allow per node. 403 | func (t *BTree) maxItems() int { 404 | return t.degree*2 - 1 405 | } 406 | 407 | // minItems returns the min number of items to allow per node (ignored for the 408 | // root node). 409 | func (t *BTree) minItems() int { 410 | return t.degree - 1 411 | } 412 | 413 | func (t *BTree) newNode() (n *node) { 414 | index := len(t.freelist) - 1 415 | if index < 0 { 416 | return &node{t: t} 417 | } 418 | t.freelist, n = t.freelist[:index], t.freelist[index] 419 | return 420 | } 421 | 422 | func (t *BTree) freeNode(n *node) { 423 | if len(t.freelist) < cap(t.freelist) { 424 | for i := range n.items { 425 | n.items[i] = nil // clear to allow GC 426 | } 427 | n.items = n.items[:0] 428 | for i := range n.children { 429 | n.children[i] = nil // clear to allow GC 430 | } 431 | n.children = n.children[:0] 432 | t.freelist = append(t.freelist, n) 433 | } 434 | } 435 | 436 | // ReplaceOrInsert adds the given item to the tree. If an item in the tree 437 | // already equals the given one, it is removed from the tree and returned. 438 | // Otherwise, nil is returned. 439 | // 440 | // nil cannot be added to the tree (will panic). 441 | func (t *BTree) ReplaceOrInsert(item Item) Item { 442 | if item == nil { 443 | panic("nil item being added to BTree") 444 | } 445 | if t.root == nil { 446 | t.root = t.newNode() 447 | t.root.items = append(t.root.items, item) 448 | t.length++ 449 | return nil 450 | } else if len(t.root.items) >= t.maxItems() { 451 | item2, second := t.root.split(t.maxItems() / 2) 452 | oldroot := t.root 453 | t.root = t.newNode() 454 | t.root.items = append(t.root.items, item2) 455 | t.root.children = append(t.root.children, oldroot, second) 456 | } 457 | out := t.root.insert(item, t.maxItems()) 458 | if out == nil { 459 | t.length++ 460 | } 461 | return out 462 | } 463 | 464 | // Delete removes an item equal to the passed in item from the tree, returning 465 | // it. If no such item exists, returns nil. 466 | func (t *BTree) Delete(item Item) Item { 467 | return t.deleteItem(item, removeItem) 468 | } 469 | 470 | // DeleteMin removes the smallest item in the tree and returns it. 471 | // If no such item exists, returns nil. 472 | func (t *BTree) DeleteMin() Item { 473 | return t.deleteItem(nil, removeMin) 474 | } 475 | 476 | // DeleteMax removes the largest item in the tree and returns it. 477 | // If no such item exists, returns nil. 478 | func (t *BTree) DeleteMax() Item { 479 | return t.deleteItem(nil, removeMax) 480 | } 481 | 482 | func (t *BTree) deleteItem(item Item, typ toRemove) Item { 483 | if t.root == nil || len(t.root.items) == 0 { 484 | return nil 485 | } 486 | out := t.root.remove(item, t.minItems(), typ) 487 | if len(t.root.items) == 0 && len(t.root.children) > 0 { 488 | oldroot := t.root 489 | t.root = t.root.children[0] 490 | t.freeNode(oldroot) 491 | } 492 | if out != nil { 493 | t.length-- 494 | } 495 | return out 496 | } 497 | 498 | // AscendRange calls the iterator for every value in the tree within the range 499 | // [greaterOrEqual, lessThan), until iterator returns false. 500 | func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) { 501 | if t.root == nil { 502 | return 503 | } 504 | t.root.iterate( 505 | func(a Item) bool { return !a.Less(greaterOrEqual) }, 506 | func(a Item) bool { return a.Less(lessThan) }, 507 | iterator) 508 | } 509 | 510 | // AscendLessThan calls the iterator for every value in the tree within the range 511 | // [first, pivot), until iterator returns false. 512 | func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator) { 513 | if t.root == nil { 514 | return 515 | } 516 | t.root.iterate( 517 | func(a Item) bool { return true }, 518 | func(a Item) bool { return a.Less(pivot) }, 519 | iterator) 520 | } 521 | 522 | // AscendGreaterOrEqual calls the iterator for every value in the tree within 523 | // the range [pivot, last], until iterator returns false. 524 | func (t *BTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) { 525 | if t.root == nil { 526 | return 527 | } 528 | t.root.iterate( 529 | func(a Item) bool { return !a.Less(pivot) }, 530 | func(a Item) bool { return true }, 531 | iterator) 532 | } 533 | 534 | // Ascend calls the iterator for every value in the tree within the range 535 | // [first, last], until iterator returns false. 536 | func (t *BTree) Ascend(iterator ItemIterator) { 537 | if t.root == nil { 538 | return 539 | } 540 | t.root.iterate( 541 | func(a Item) bool { return true }, 542 | func(a Item) bool { return true }, 543 | iterator) 544 | } 545 | 546 | // Get looks for the key item in the tree, returning it. It returns nil if 547 | // unable to find that item. 548 | func (t *BTree) Get(key Item) Item { 549 | if t.root == nil { 550 | return nil 551 | } 552 | return t.root.get(key) 553 | } 554 | 555 | // Has returns true if the given key is in the tree. 556 | func (t *BTree) Has(key Item) bool { 557 | return t.Get(key) != nil 558 | } 559 | 560 | // Len returns the number of items currently in the tree. 561 | func (t *BTree) Len() int { 562 | return t.length 563 | } 564 | 565 | // Int implements the Item interface for integers. 566 | type Int int 567 | 568 | // Less returns true if int(a) < int(b). 569 | func (a Int) Less(b Item) bool { 570 | return a < b.(Int) 571 | } -------------------------------------------------------------------------------- /trees/kd-tree.go: -------------------------------------------------------------------------------- 1 | // source: http://rosettacode.org/wiki/K-d_tree#Go 2 | 3 | // Implmentation following pseudocode from "An intoductory tutorial on kd-trees" 4 | // by Andrew W. Moore, Carnegie Mellon University, PDF accessed from 5 | // http://www.autonlab.org/autonweb/14665 6 | 7 | package trees 8 | 9 | import ( 10 | "fmt" 11 | "math" 12 | "math/rand" 13 | "sort" 14 | ) 15 | 16 | // point is a k-dimensional point. 17 | type point []float64 18 | 19 | // sqd returns the square of the euclidean distance. 20 | func (p point) sqd(q point) float64 { 21 | var sum float64 22 | for dim, pCoord := range p { 23 | d := pCoord - q[dim] 24 | sum += d * d 25 | } 26 | return sum 27 | } 28 | 29 | // kdNode following field names in the paper. 30 | // rangeElt would be whatever data is associated with the point. we don't 31 | // bother with it for this example. 32 | type kdNode struct { 33 | domElt point 34 | split int 35 | left, right *kdNode 36 | } 37 | 38 | type kdTree struct { 39 | n *kdNode 40 | bounds hyperRect 41 | } 42 | 43 | type hyperRect struct { 44 | min, max point 45 | } 46 | 47 | // Go slices are reference objects. The data must be copied if you want 48 | // to modify one without modifying the original. 49 | func (hr hyperRect) copy() hyperRect { 50 | return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} 51 | } 52 | 53 | // newKd constructs a kdTree from a list of points, also associating the 54 | // bounds of the tree. The bounds could be computed of course, but in this 55 | // example we know them already. The algorithm is table 6.3 in the paper. 56 | func newKd(pts []point, bounds hyperRect) kdTree { 57 | var nk2 func([]point, int) *kdNode 58 | nk2 = func(exset []point, split int) *kdNode { 59 | if len(exset) == 0 { 60 | return nil 61 | } 62 | // pivot choosing procedure. we find median, then find largest 63 | // index of points with median value. this satisfies the 64 | // inequalities of steps 6 and 7 in the algorithm. 65 | sort.Sort(part{exset, split}) 66 | m := len(exset) / 2 67 | d := exset[m] 68 | for m+1 < len(exset) && exset[m+1][split] == d[split] { 69 | m++ 70 | } 71 | // next split 72 | s2 := split + 1 73 | if s2 == len(d) { 74 | s2 = 0 75 | } 76 | return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} 77 | } 78 | return kdTree{nk2(pts, 0), bounds} 79 | } 80 | 81 | // a container type used for sorting. it holds the points to sort and 82 | // the dimension to use for the sort key. 83 | type part struct { 84 | pts []point 85 | dPart int 86 | } 87 | 88 | // satisfy sort.Interface 89 | func (p part) Len() int { return len(p.pts) } 90 | func (p part) Less(i, j int) bool { 91 | return p.pts[i][p.dPart] < p.pts[j][p.dPart] 92 | } 93 | func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } 94 | 95 | // nearest. find nearest neighbor. return values are: 96 | // nearest neighbor--the point within the tree that is nearest p. 97 | // square of the distance to that point. 98 | // a count of the nodes visited in the search. 99 | func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { 100 | return nn(t.n, p, t.bounds, math.Inf(1)) 101 | } 102 | 103 | // algorithm is table 6.4 from the paper, with the addition of counting 104 | // the number nodes visited. 105 | func nn(kd *kdNode, target point, hr hyperRect, 106 | maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { 107 | if kd == nil { 108 | return nil, math.Inf(1), 0 109 | } 110 | nodesVisited++ 111 | s := kd.split 112 | pivot := kd.domElt 113 | leftHr := hr.copy() 114 | rightHr := hr.copy() 115 | leftHr.max[s] = pivot[s] 116 | rightHr.min[s] = pivot[s] 117 | targetInLeft := target[s] <= pivot[s] 118 | var nearerKd, furtherKd *kdNode 119 | var nearerHr, furtherHr hyperRect 120 | if targetInLeft { 121 | nearerKd, nearerHr = kd.left, leftHr 122 | furtherKd, furtherHr = kd.right, rightHr 123 | } else { 124 | nearerKd, nearerHr = kd.right, rightHr 125 | furtherKd, furtherHr = kd.left, leftHr 126 | } 127 | var nv int 128 | nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) 129 | nodesVisited += nv 130 | if distSqd < maxDistSqd { 131 | maxDistSqd = distSqd 132 | } 133 | d := pivot[s] - target[s] 134 | d *= d 135 | if d > maxDistSqd { 136 | return 137 | } 138 | if d = pivot.sqd(target); d < distSqd { 139 | nearest = pivot 140 | distSqd = d 141 | maxDistSqd = distSqd 142 | } 143 | tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) 144 | nodesVisited += nv 145 | if tempSqd < distSqd { 146 | nearest = tempNearest 147 | distSqd = tempSqd 148 | } 149 | return 150 | } 151 | 152 | func randomPt(dim int) point { 153 | p := make(point, dim) 154 | for d := range p { 155 | p[d] = rand.Float64() 156 | } 157 | return p 158 | } 159 | 160 | func randomPts(dim, n int) []point { 161 | p := make([]point, n) 162 | for i := range p { 163 | p[i] = randomPt(dim) 164 | } 165 | return p 166 | } 167 | 168 | func showNearest(heading string, kd kdTree, p point) { 169 | fmt.Println() 170 | fmt.Println(heading) 171 | fmt.Println("point: ", p) 172 | nn, ssq, nv := kd.nearest(p) 173 | fmt.Println("nearest neighbor:", nn) 174 | fmt.Println("distance: ", math.Sqrt(ssq)) 175 | fmt.Println("nodes visited: ", nv) 176 | } 177 | --------------------------------------------------------------------------------