trie-substring-search 0.1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5923666c4e83e361fcc051b410f1238400ff1c088438118d3f1cf00e82801399
4
+ data.tar.gz: ccf9b0af6f30c421d71faad210572978f957d40cedeed7e6938bfb4f736b39a2
5
+ SHA512:
6
+ metadata.gz: 5158ee96b40d03627b098f8be180ef25e9abbb8787c226fa0da5c6d57557d2d2991a487ff8973447380649c382c3296a587b18ddef30ee91793a24cd0fc09fde
7
+ data.tar.gz: 66c0c9a4a1e22d9f2b543a978fe16cf0f65dfdaf13fe5e0c861ce283db53bdf3a1d17c146e3be040a5c32b242563a2ab798a91ef331c090d961306c73e9beae4
@@ -0,0 +1,27 @@
1
+ kind: pipeline
2
+ name: default
3
+
4
+ steps:
5
+ - name: install
6
+ image: ruby
7
+ volumes:
8
+ - name: bundle
9
+ path: /usr/local/bundle
10
+ commands:
11
+ - bundle install --jobs=3 --retry=3
12
+
13
+ - name: test
14
+ image: ruby
15
+ environment:
16
+ CODECOV_TOKEN:
17
+ from_secret: CODECOV_TOKEN
18
+ CI: true
19
+ volumes:
20
+ - name: bundle
21
+ path: /usr/local/bundle
22
+ commands:
23
+ - rake
24
+
25
+ volumes:
26
+ - name: bundle
27
+ temp: {}
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /spec/tss/fixtures/*
10
+ /spec/tss/trie/search_high_load_spec.rb
11
+ # rspec failure tracking
12
+ .rspec_status
13
+ *.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.1
7
+ before_install: gem install bundler -v 1.17.2
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source 'https://rubygems.org'
2
+
3
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in tss.gemspec
6
+ gemspec
@@ -0,0 +1,95 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ trie-substring-search (0.1.0.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ansi (1.5.0)
10
+ ast (2.4.0)
11
+ benchmark-malloc (0.1.0)
12
+ benchmark-perf (0.5.0)
13
+ benchmark-trend (0.3.0)
14
+ codecov (0.1.14)
15
+ json
16
+ simplecov
17
+ url
18
+ coderay (1.1.2)
19
+ diff-lcs (1.3)
20
+ docile (1.3.1)
21
+ hirb (0.7.3)
22
+ jaro_winkler (1.5.2)
23
+ json (2.2.0)
24
+ method_source (0.9.2)
25
+ parallel (1.17.0)
26
+ parser (2.6.3.0)
27
+ ast (~> 2.4.0)
28
+ pry (0.12.2)
29
+ coderay (~> 1.1.0)
30
+ method_source (~> 0.9.0)
31
+ psych (3.1.0)
32
+ rainbow (3.0.0)
33
+ rake (10.5.0)
34
+ rspec (3.8.0)
35
+ rspec-core (~> 3.8.0)
36
+ rspec-expectations (~> 3.8.0)
37
+ rspec-mocks (~> 3.8.0)
38
+ rspec-benchmark (0.5.0)
39
+ benchmark-malloc (~> 0.1.0)
40
+ benchmark-perf (~> 0.5.0)
41
+ benchmark-trend (~> 0.3.0)
42
+ rspec (>= 3.0.0, < 4.0.0)
43
+ rspec-collection_matchers (1.1.3)
44
+ rspec-expectations (>= 2.99.0.beta1)
45
+ rspec-core (3.8.0)
46
+ rspec-support (~> 3.8.0)
47
+ rspec-expectations (3.8.3)
48
+ diff-lcs (>= 1.2.0, < 2.0)
49
+ rspec-support (~> 3.8.0)
50
+ rspec-mocks (3.8.0)
51
+ diff-lcs (>= 1.2.0, < 2.0)
52
+ rspec-support (~> 3.8.0)
53
+ rspec-support (3.8.0)
54
+ rubocop (0.67.2)
55
+ jaro_winkler (~> 1.5.1)
56
+ parallel (~> 1.10)
57
+ parser (>= 2.5, != 2.5.1.1)
58
+ psych (>= 3.1.0)
59
+ rainbow (>= 2.2.2, < 4.0)
60
+ ruby-progressbar (~> 1.7)
61
+ unicode-display_width (>= 1.4.0, < 1.6)
62
+ rubocop-performance (1.1.0)
63
+ rubocop (>= 0.67.0)
64
+ ruby-progressbar (1.10.0)
65
+ simplecov (0.16.1)
66
+ docile (~> 1.1)
67
+ json (>= 1.8, < 3)
68
+ simplecov-html (~> 0.10.0)
69
+ simplecov-console (0.4.2)
70
+ ansi
71
+ hirb
72
+ simplecov
73
+ simplecov-html (0.10.2)
74
+ unicode-display_width (1.5.0)
75
+ url (0.3.2)
76
+
77
+ PLATFORMS
78
+ ruby
79
+
80
+ DEPENDENCIES
81
+ bundler (~> 2.0.1)
82
+ codecov (~> 0.1)
83
+ pry (~> 0.12)
84
+ rake (~> 10.0)
85
+ rspec (~> 3.0)
86
+ rspec-benchmark (~> 0.5.0)
87
+ rspec-collection_matchers (~> 1.1.0)
88
+ rubocop (~> 0.67.0)
89
+ rubocop-performance (~> 1.1.0)
90
+ simplecov (~> 0.16.0)
91
+ simplecov-console (~> 0.4.0)
92
+ trie-substring-search!
93
+
94
+ BUNDLED WITH
95
+ 2.0.1
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,91 @@
1
+ # Trie Substring Search
2
+
3
+ [![Build Status](https://cloud.drone.io/api/badges/sbezugliy/trie-substring-search/status.svg)](https://cloud.drone.io/sbezugliy/trie-substring-search)
4
+
5
+ [![Maintainability](https://api.codeclimate.com/v1/badges/94c864de2611aedac431/maintainability)](https://codeclimate.com/github/sbezugliy/trie-substring-search/maintainability)
6
+ [![codecov](https://codecov.io/gh/sbezugliy/trie-substring-search/branch/master/graph/badge.svg)](https://codecov.io/gh/sbezugliy/trie-substring-search)
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'trie-substring-search'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ $ bundle
19
+
20
+ Or install it yourself as:
21
+
22
+ $ gem install trie-substring-search
23
+
24
+ ## Usage
25
+
26
+ ```ruby
27
+ # Array of words in the dictionary
28
+ dictionary = %w[he she her his him he they their she]
29
+ # Initialize trie
30
+ # types of trie to build :full, :flat(WIP) and :aho_corasick(WIP)
31
+ tss = TSS::Trie.new(dictionary, :full)
32
+ # Parse text and receive array of all occurrences of words in texts with indexes of word in dictionary
33
+ tss.parse('he their them height have then their shelter')
34
+ # => [{:word=>"he", :indexes=>[0, 5]},
35
+ # {:word=>"their", :indexes=>[7]},
36
+ # {:word=>"he", :indexes=>[0, 5]},
37
+ # {:word=>"he", :indexes=>[0, ''$'\200\274\240\235\357''U'5]},
38
+ # {:word=>"he", :indexes=>[0, 5]},
39
+ # {:word=>"he", :indexes=>[0, 5]},
40
+ # {:word=>"their", :indexes=>[7]},
41
+ # {:word=>"he", :indexes=>[0, 5]},
42
+ # {:word=>"she", :indexes=>[1, 8]},
43
+ # {:word=>"he", :indexes=>[0, 5]}]
44
+ # Add additional words to the dictionary
45
+ tss.extend_dictionary(["our", "it", "them"])
46
+ # Get end vertex of word 'they'
47
+ vertex = tss.root.get_child('s').get_child('h').get_child('e')
48
+ # => #<ACT::Vertex:0x000055cabb2399d0
49
+ # @char="e",
50
+ # @children=[],
51
+ # @end_indexes=[1, 8],
52
+ # @parent=
53
+ # #<ACT::Vertex:0x000055cabb239ac0
54
+ # @char="h",
55
+ # @children=[#<ACT::Vertex:0x000055cabb2399d0 ...>],
56
+ # @end_indexes=[],
57
+ # @parent=
58
+ # #<ACT::Vertex:0x000055cabb239bb0
59
+ # @char="s",
60
+ # @children=[#<ACT::Vertex:0x000055cabb239ac0 ...>],
61
+ # get array of indexes of word
62
+ vertex.end_indexes
63
+ # => [1, 8]
64
+ # Recover word from trie with indexes in dictionary
65
+ tss.backtrace_to_word(vertex)
66
+ # => {:word=>"she", :indexes=>[1, 8]}
67
+ ```
68
+
69
+ Index of word in dictionary can be used to get relations with additional array with external data(or collection, or can be easily replaced by foreign key in the future). If dictionary contain duplicates, then you will get few indexes in result.
70
+
71
+ ## Benchmark
72
+
73
+ dictionary: 100000 words
74
+ number of executions with uniq text: 44555
75
+ results of benchmark:
76
+
77
+ user system total real
78
+ 1.749733 0.116561 1.866294 ( 1.876876)
79
+
80
+ ## Development
81
+
82
+ ## Contributing
83
+
84
+ ### TBD Improvements:
85
+
86
+ - TODO: Mode providing ability to return whole words, that contain substring from dictionary
87
+ - TODO: Suffix references is not implemented. Just now it contains full syntax tree, so it is less memory efficient then original Aho-Corasick algorithm.
88
+ - TODO: Maybe, will be good to implement next features for trie build stage:
89
+ - post optimization of vertex connections, creating suffixes
90
+ - some parallelism
91
+ - pre optimization of a dictionary.
@@ -0,0 +1,6 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task default: :spec
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'tss/tss'
5
+ require 'tss/tries/full'
6
+ require 'tss/tries/flat'
7
+ require 'tss/tries/ac'
8
+ require 'tss/tries/base'
9
+ require 'tss/trie'
10
+ require 'tss/link'
11
+ require 'tss/vertex'
12
+
13
+ # You can add fixtures and/or initialization code here to make experimenting
14
+ # with your gem easier. You can also use a different console, if you like.
15
+
16
+ # (If you use this, don't forget to add pry to your Gemfile!)
17
+ # require "pry"
18
+ # Pry.start
19
+
20
+ require 'pry'
21
+ Pry.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,23 @@
1
+ module TSS
2
+ ##
3
+ # Class representing links(suffixes) between vertexes
4
+ class Link
5
+ ##
6
+ # Linked vertex
7
+ attr_accessor :vertex
8
+ ##
9
+ # Character to simplify search
10
+ attr_reader :char
11
+ ##
12
+ # Index of word in dictionary if vertex is ending, or nil if vertex is suffix
13
+ attr_accessor :end_index
14
+
15
+ ##
16
+ # Create new ACT::Link object
17
+ def initialize(vertex, end_index = nil)
18
+ @vertex = vertex
19
+ @char = @vertex.char
20
+ @end_index = end_index
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,71 @@
1
+ # TSS module
2
+ module TSS
3
+ ##
4
+ # Main class for creating Trie Substring Search from array of words of dictionary
5
+ class Trie
6
+ ##
7
+ # Root vertex
8
+ attr_reader :root
9
+ ##
10
+ # Dictionary attribute
11
+ attr_reader :dictionary
12
+ ##
13
+ # Trie attribute
14
+ attr_reader :trie
15
+ ##
16
+ # Trie class reference switched by type
17
+ attr_reader :trie_class
18
+ ##
19
+ # Trie class instance
20
+ attr_reader :trie_instance
21
+ ##
22
+ # Initialize new trie and fill it with words from dictionary
23
+ def initialize(dictionary, type = :full)
24
+ switch_trie_type(type)
25
+ @root = TSS::Vertex.new
26
+ @dictionary = dictionary
27
+ build_trie
28
+ end
29
+
30
+ ##
31
+ # Executes text analyzis and returns map occurring words with indexes from dictionary
32
+ def parse(text)
33
+ @trie_instance.parse(text)
34
+ end
35
+
36
+ ##
37
+ # Returns hash with word and indexes at dictionary
38
+ # * Ending vertex of chain should be used as argument, it means that it should
39
+ # contain at least one value in the array of end_indexes attribute
40
+ def backtrace_to_word(vertex)
41
+ @trie_instance.backtrace_to_word(vertex)
42
+ end
43
+
44
+ ##
45
+ # Adds additional words(chains of vertexes) to the trie object
46
+ # * Argument should be array of words
47
+ # Example:
48
+ # >> tss.extend_dictionary(["our", "it", "them"])
49
+ def extend_dictionary(dict)
50
+ @trie_instance.extend_dictionary(dict)
51
+ end
52
+
53
+ private
54
+
55
+ def build_trie
56
+ @trie_instance = @trie_class.new(@dictionary, @root)
57
+ end
58
+
59
+ def switch_trie_type(type)
60
+ @trie_class = TSS::Tries.const_get(trie_symbol(type), @root)
61
+ end
62
+
63
+ def trie_symbol(type)
64
+ return :Full if type == :full
65
+ return :AC if type == :aho_corasick
66
+ return :Flat if type == :flat
67
+
68
+ raise ArgumentError, 'Wrong trie type. Possible is: :full, :flat or :aho_corasick'
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,26 @@
1
+ module TSS
2
+ module Tries
3
+ ##
4
+ # Aho-Corasick trie class
5
+ class AC < Base
6
+ ##
7
+ # Executes text analyze and returns map occurring words with indexes from dictionary
8
+
9
+ def parse
10
+ raise 'WIP'
11
+ end
12
+
13
+ ##
14
+ # Returns hash with word and indexes at dictionary
15
+ def backtrace_to_word
16
+ raise 'WIP'
17
+ end
18
+
19
+ ##
20
+ # Adds additional words(chains of vertexes) to the trie object
21
+ def extend_dictionay
22
+ raise 'WIP'
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,45 @@
1
+ # TSS module
2
+ module TSS
3
+ module Tries
4
+ ##
5
+ # Main class for creating Aho-Corasick Trie from array of words of dictionary
6
+ class Base
7
+ ##
8
+ # Root vertex
9
+ attr_reader :root
10
+ ##
11
+ # Dictionary attribute
12
+ attr_reader :dictionary
13
+ ##
14
+ # Trie attribute
15
+ attr_reader :trie
16
+
17
+ ##
18
+ # Initialize new trie and fill it with words from dictionary
19
+ #
20
+ # Remarks:
21
+ # * dictioanry is array of characters
22
+ # * if indexing is important array should not be sorted
23
+ # * word from sentence may contain spaces and special characters, so
24
+ # one "word" can be the whole sentence
25
+ # * word can be an integer, but result will be converted to the string
26
+ #
27
+ # Example:
28
+ # >> TSS.new(["abc", "cde", 8, "ad f", "wer\nm"])
29
+ #
30
+ # Arguments:
31
+ # dictionary: (Array)
32
+ def initialize(dictionary, root_vertex)
33
+ @root = root_vertex
34
+ @dictionary = dictionary
35
+ @trie = build_trie
36
+ end
37
+
38
+ private
39
+
40
+ def build_trie
41
+ @root
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,27 @@
1
+ # TSS module
2
+ module TSS
3
+ module Tries
4
+ ##
5
+ # Main class for creating Flat Trie from array of words of dictionary
6
+ class Flat < Base
7
+ ##
8
+ # Executes text analyze and returns map occurring words with indexes from dictionary
9
+
10
+ def parse(_text)
11
+ raise 'WIP'
12
+ end
13
+
14
+ ##
15
+ # Returns hash with word and indexes at dictionary
16
+ def backtrace_to_word(_vertex)
17
+ raise 'WIP'
18
+ end
19
+
20
+ ##
21
+ # Adds additional words(chains of vertexes) to the trie object
22
+ def extend_dictionary(_dict)
23
+ raise 'WIP'
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,130 @@
1
+ # TSS module
2
+ module TSS
3
+ module Tries
4
+ ##
5
+ # Main class for creating Full Trie from array of words of dictionary
6
+ class Full < Base
7
+ ##
8
+ # Executes text analyze and returns map occurring words with indexes from dictionary
9
+ # Example:
10
+ # >> tss.parse('he their them height have then their shelter')
11
+ # => [ {:word=>"he", :indexes=>[0, 5]},
12
+ # {:word=>"their", :indexes=>[7]},
13
+ # {:word=>"he", :indexes=>[0, 5]},
14
+ # {:word=>"he", :indexes=>[0, 5]},
15
+ # {:word=>"he", :indexes=>[0, 5]},
16
+ # {:word=>"he", :indexes=>[0, 5]},
17
+ # {:word=>"their", :indexes=>[7]},
18
+ # {:word=>"he", :indexes=>[0, 5]},
19
+ # {:word=>"she", :indexes=>[1, 8]},
20
+ # {:word=>"he", :indexes=>[0, 5]}]
21
+ # Arguments:
22
+ # text: (String)
23
+ def parse(text)
24
+ text = text.to_s.split('')
25
+ vm = vertex_map(text) { :vertex }
26
+ exec_branches(text, vm).flatten.compact
27
+ end
28
+
29
+ ##
30
+ # Returns hash with vertexes that represents letters of word and indexes of word in dictionary
31
+ # * Ending vertex of chain should be used as argument, it means that it should
32
+ # contain at least one value in the array of end_indexes attribute
33
+ # Example:
34
+ # backtrace_to_word(vertex)
35
+ # Arguments:
36
+ # vertex: (TSS::Vertex) - ending vertex of chain of letters
37
+ def backtrace_to_word(vertex)
38
+ if vertex.end_indexes.empty?
39
+ raise 'Argument should be ending vertex of chain, and contain at'\
40
+ 'least one value in the array of end_indexes attribute'
41
+ else
42
+ chain = backtrace(vertex)
43
+ {
44
+ word: chain.reduce('') { |acc, v| acc << v.char },
45
+ indexes: chain.last.end_indexes
46
+ }
47
+ end
48
+ end
49
+
50
+ ##
51
+ # Adds additional words(chains of vertexes) to the trie object
52
+ # * Argument should be array of words
53
+ # Example:
54
+ # >> tss.extend_dictionary(["our", "it", "them"])
55
+ def extend_dictionary(dict)
56
+ build_trie(dict)
57
+ end
58
+
59
+ private
60
+
61
+ def exec_branches(text, vertex_map)
62
+ vertex_map.map do |b|
63
+ b[:indexes].map do |index|
64
+ search(b[:key], text[index + 1..-1])
65
+ end
66
+ end
67
+ end
68
+
69
+ def search(vertex, text)
70
+ result = []
71
+ return result unless vertex
72
+
73
+ result << backtrace_to_word(vertex) if end_vertex?(vertex)
74
+ return result if vertex.children.empty?
75
+
76
+ ending = search_rest(vertex, text)
77
+ !ending.empty? ? (result + ending) : result
78
+ end
79
+
80
+ def search_rest(vertex, text)
81
+ result = []
82
+ text.each do |char|
83
+ current_vertex = vertex.get_child(char)
84
+ break if current_vertex.nil?
85
+
86
+ result << backtrace_to_word(current_vertex) if end_vertex?(current_vertex)
87
+ break if current_vertex.children.empty?
88
+
89
+ vertex = current_vertex
90
+ end
91
+ result
92
+ end
93
+
94
+ def vertex_map(text)
95
+ @trie.children.map do |vertex|
96
+ {
97
+ key: vertex.send(yield),
98
+ indexes: text.collect.with_index { |c, i| i if c == vertex.char }.compact
99
+ }
100
+ end
101
+ end
102
+
103
+ def end_vertex?(vertex)
104
+ !vertex.end_indexes.empty?
105
+ end
106
+
107
+ def backtrace(vertex)
108
+ result = !vertex.nil? ? [vertex] : []
109
+ until vertex.parent.nil?
110
+ result << vertex.parent unless vertex.parent.char.nil?
111
+ vertex = vertex.parent
112
+ end
113
+ result.reverse
114
+ end
115
+
116
+ def build_trie(dict = @dictionary)
117
+ parent = @root
118
+ dict.each_with_index do |word, index|
119
+ word = word.to_s
120
+ word.to_s.each_char.with_index do |char, char_index|
121
+ end_index = char_index == (word.length - 1) ? index : nil
122
+ @vertex = (char_index.zero? ? @root : parent)
123
+ parent = @vertex.add_child(char, end_index)
124
+ end
125
+ end
126
+ @root
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,11 @@
1
+ require 'tss/version'
2
+ require 'tss/trie'
3
+ require 'tss/tries/base'
4
+ require 'tss/tries/full'
5
+ require 'tss/tries/flat'
6
+ require 'tss/tries/ac'
7
+ require 'tss/vertex'
8
+ require 'tss/link'
9
+ ##
10
+ # Main module for Trie Substring Search
11
+ module TSS; end
@@ -0,0 +1,3 @@
1
+ module TSS
2
+ VERSION = '0.1.0.0'.freeze
3
+ end
@@ -0,0 +1,95 @@
1
+ # TSS module
2
+ module TSS
3
+ ##
4
+ # Trie vertex class
5
+ class Vertex
6
+ ##
7
+ # Reference to the root vertex of the trie
8
+ attr_accessor :root
9
+ ##
10
+ # Reference to the parent TSS::Vertex
11
+ attr_accessor :parent
12
+ ##
13
+ # Array of children TSS::Vertex references for nested models(full trie, Aho-Corasick trie)
14
+ # or as list of nested vertexes of root vertex of flat trie
15
+ attr_reader :children
16
+ ##
17
+ # Array of TSS::Vertex links for flat trie model, also used as suffixes of Aho-Corasick trie
18
+ attr_reader :links
19
+ ##
20
+ # Array of indexes of word in dictionary
21
+ # Empty if it is intermediate TSS::Vertex in chain
22
+ attr_accessor :end_indexes
23
+ ##
24
+ # Letter representing this vertex
25
+ attr_accessor :char
26
+
27
+ ##
28
+ # Initializes new vertex
29
+ # * +parent+ is parent TSS::Vertex
30
+ # Example:
31
+ # >> TSS::Vertex.new(@root_vertex)
32
+ # >> TSS::Vertex.new(@root_vertex)
33
+ # Optional arguments:
34
+ # parent: (TSS::Vertex)
35
+ def initialize(parent = nil)
36
+ @char = nil
37
+ @parent = parent
38
+ @children = []
39
+ @links = []
40
+ @end_indexes = []
41
+ yield(self) if block_given?
42
+ end
43
+
44
+ ##
45
+ # Initializes new TSS::Vertex and adds it to the parent attribute
46
+ def add_child(char, end_index)
47
+ child = get_child(char)
48
+ if child
49
+ child.end_indexes << end_index unless end_index.nil?
50
+ child
51
+ else
52
+ init_subchild(char, end_index)
53
+ end
54
+ end
55
+
56
+ ##
57
+ # Returns child TSS::Vertex by letter, from children attribute
58
+ def get_child(char)
59
+ @children.find { |c| c.char == char }
60
+ end
61
+
62
+ ##
63
+ # Adds reference to the linked vertexes
64
+ def add_link(vertex, end_index = nil)
65
+ @links << TSS::Link.new(vertex, end_index)
66
+ end
67
+
68
+ ##
69
+ # Returns link by character
70
+ def get_link(char)
71
+ @links.find { |l| l.char == char }
72
+ end
73
+
74
+ ##
75
+ # Returns array of characters from array of children TSS::Vertex
76
+ def children_chars
77
+ @children.map(&:char)
78
+ end
79
+
80
+ def vertex
81
+ self
82
+ end
83
+
84
+ private
85
+
86
+ def init_subchild(char, end_index)
87
+ child = self.class.new(self)
88
+ child.char = char
89
+ child.root = @root
90
+ child.end_indexes << end_index unless end_index.nil?
91
+ @children << child
92
+ child
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,56 @@
1
+ lib = File.expand_path('lib', __dir__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require './lib/tss/version'
4
+ require './lib/tss/tss'
5
+ require './lib/tss/trie'
6
+ require './lib/tss/tries/base'
7
+ require './lib/tss/tries/ac'
8
+ require './lib/tss/tries/full'
9
+ require './lib/tss/tries/flat'
10
+ require './lib/tss/vertex'
11
+ Gem::Specification.new do |spec|
12
+ spec.name = 'trie-substring-search'
13
+ spec.version = TSS::VERSION
14
+ spec.authors = ['Sergey Bezugliy']
15
+ spec.email = ['s.bezugliy@gmail.com']
16
+ spec.homepage = 'https://codenv.top/projects/trie-substring-search'
17
+ spec.summary = 'Trie based substring search algorithm implementation'
18
+ spec.license = 'Apache-2.0'
19
+ spec.description = <<-DESCRIPTION
20
+ This gem provides ruby library with algorithms for trie based
21
+ substring search.
22
+ DESCRIPTION
23
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
24
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
25
+ if spec.respond_to?(:metadata)
26
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
27
+
28
+ spec.metadata['homepage_uri'] = spec.homepage
29
+ spec.metadata['source_code_uri'] = 'https://github.com/sbezugliy/trie-substring-search'
30
+ # spec.metadata['changelog_uri'] = 'https://github.com/sbezugliy/trie-substring-search/changelog.md'
31
+ else
32
+ raise 'RubyGems 2.0 or newer is required to protect against' \
33
+ 'public gem pushes.'
34
+ end
35
+
36
+ # Specify which files should be added to the gem when it is released.
37
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
38
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
39
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
40
+ end
41
+ spec.bindir = 'exe'
42
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
43
+ spec.require_paths = ['lib']
44
+
45
+ spec.add_development_dependency 'bundler', '~> 2.0.1'
46
+ spec.add_development_dependency 'codecov', '~> 0.1'
47
+ spec.add_development_dependency 'pry', '~> 0.12'
48
+ spec.add_development_dependency 'rake', '~> 10.0'
49
+ spec.add_development_dependency 'rspec', '~> 3.0'
50
+ spec.add_development_dependency 'rspec-benchmark', '~> 0.5.0'
51
+ spec.add_development_dependency 'rspec-collection_matchers', '~> 1.1.0'
52
+ spec.add_development_dependency 'rubocop', '~> 0.67.0'
53
+ spec.add_development_dependency 'rubocop-performance', '~> 1.1.0'
54
+ spec.add_development_dependency 'simplecov', '~> 0.16.0'
55
+ spec.add_development_dependency 'simplecov-console', '~> 0.4.0'
56
+ end
metadata ADDED
@@ -0,0 +1,223 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: trie-substring-search
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Sergey Bezugliy
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-05-11 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 2.0.1
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 2.0.1
27
+ - !ruby/object:Gem::Dependency
28
+ name: codecov
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.1'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: pry
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.12'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.12'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec-benchmark
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: 0.5.0
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: 0.5.0
97
+ - !ruby/object:Gem::Dependency
98
+ name: rspec-collection_matchers
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: 1.1.0
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: 1.1.0
111
+ - !ruby/object:Gem::Dependency
112
+ name: rubocop
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: 0.67.0
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: 0.67.0
125
+ - !ruby/object:Gem::Dependency
126
+ name: rubocop-performance
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - "~>"
130
+ - !ruby/object:Gem::Version
131
+ version: 1.1.0
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - "~>"
137
+ - !ruby/object:Gem::Version
138
+ version: 1.1.0
139
+ - !ruby/object:Gem::Dependency
140
+ name: simplecov
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - "~>"
144
+ - !ruby/object:Gem::Version
145
+ version: 0.16.0
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - "~>"
151
+ - !ruby/object:Gem::Version
152
+ version: 0.16.0
153
+ - !ruby/object:Gem::Dependency
154
+ name: simplecov-console
155
+ requirement: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - "~>"
158
+ - !ruby/object:Gem::Version
159
+ version: 0.4.0
160
+ type: :development
161
+ prerelease: false
162
+ version_requirements: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - "~>"
165
+ - !ruby/object:Gem::Version
166
+ version: 0.4.0
167
+ description: |2
168
+ This gem provides ruby library with algorithms for trie based
169
+ substring search.
170
+ email:
171
+ - s.bezugliy@gmail.com
172
+ executables: []
173
+ extensions: []
174
+ extra_rdoc_files: []
175
+ files:
176
+ - ".drone.yml"
177
+ - ".gitignore"
178
+ - ".rspec"
179
+ - ".travis.yml"
180
+ - Gemfile
181
+ - Gemfile.lock
182
+ - LICENSE
183
+ - README.md
184
+ - Rakefile
185
+ - bin/console
186
+ - bin/setup
187
+ - lib/tss/link.rb
188
+ - lib/tss/trie.rb
189
+ - lib/tss/tries/ac.rb
190
+ - lib/tss/tries/base.rb
191
+ - lib/tss/tries/flat.rb
192
+ - lib/tss/tries/full.rb
193
+ - lib/tss/tss.rb
194
+ - lib/tss/version.rb
195
+ - lib/tss/vertex.rb
196
+ - tss.gemspec
197
+ homepage: https://codenv.top/projects/trie-substring-search
198
+ licenses:
199
+ - Apache-2.0
200
+ metadata:
201
+ allowed_push_host: https://rubygems.org
202
+ homepage_uri: https://codenv.top/projects/trie-substring-search
203
+ source_code_uri: https://github.com/sbezugliy/trie-substring-search
204
+ post_install_message:
205
+ rdoc_options: []
206
+ require_paths:
207
+ - lib
208
+ required_ruby_version: !ruby/object:Gem::Requirement
209
+ requirements:
210
+ - - ">="
211
+ - !ruby/object:Gem::Version
212
+ version: '0'
213
+ required_rubygems_version: !ruby/object:Gem::Requirement
214
+ requirements:
215
+ - - ">="
216
+ - !ruby/object:Gem::Version
217
+ version: '0'
218
+ requirements: []
219
+ rubygems_version: 3.0.1
220
+ signing_key:
221
+ specification_version: 4
222
+ summary: Trie based substring search algorithm implementation
223
+ test_files: []