-
Notifications
You must be signed in to change notification settings - Fork 77
Trie #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Trie #27
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
/// Trie is an ordered tree data structure used to store a dynamic set | ||
/// or associative array where the keys are usually strings. | ||
class Trie<V extends Comparable> { | ||
/// Root of the trie. | ||
TrieNode root; | ||
|
||
/// Separates the value into it's components. | ||
final Function splitter; | ||
|
||
List _components; | ||
|
||
/// Initialises trie with custom set of values. | ||
Trie(Set components, this.splitter) { | ||
_components = [...components]; | ||
} | ||
|
||
/// Generates trie of lower-case alphabets. | ||
Trie.ofAlphabets() | ||
: this({...List.generate(26, (i) => String.fromCharCode(97 + i))}, | ||
(value) => value.split('')); | ||
|
||
/// Returns the set of [components] that make up a value. | ||
Set<V> get components => {..._components}; | ||
|
||
/// Tests if this trie is empty. | ||
bool get isEmpty => root?.children == null ? true : false; | ||
|
||
/// Adds a [value] to the trie. | ||
void add(V value) { | ||
var list = _split(value); | ||
if (isEmpty) { | ||
root ??= TrieNode({..._components}); | ||
} | ||
_add(root, list); | ||
} | ||
|
||
/// Checks if [value] is contained in the trie. | ||
bool contains(V value) { | ||
var list = _split(value); | ||
return isEmpty ? false : _contains(root, list); | ||
} | ||
|
||
/// Deletes [value] from the trie. | ||
void delete(V value) { | ||
var list = _split(value); | ||
var returnValue = _delete(root, list); | ||
returnValue ?? nullify(); | ||
} | ||
|
||
/// Empty the trie. | ||
void nullify() => root?.children = null; | ||
|
||
/// Traverses the path following [value] | ||
/// and marks `node.isValue` to true at end. | ||
void _add(TrieNode node, List<V> value) { | ||
if (value.isEmpty) { | ||
node.isValue = true; | ||
return; | ||
} | ||
var path = _indexOf(value.first); | ||
value = value.sublist(1); | ||
|
||
if (node.children[path] == null) { | ||
node.children[path] = TrieNode(components); | ||
} | ||
|
||
_add(node.children[path], value); | ||
} | ||
|
||
bool _contains(TrieNode node, List<V> value) { | ||
if (value.isEmpty) { | ||
return node.isValue; | ||
} | ||
var path = _indexOf(value.first); | ||
value = value.sublist(1); | ||
|
||
if (node.children[path] != null) { | ||
return _contains(node.children[path], value); | ||
} else { | ||
return false; | ||
} | ||
} | ||
|
||
/// Traverses the path following [value] and marks | ||
/// `node.isValue` to `false` at end. Deletes values eagerly i.e. | ||
/// cleans up any parent nodes that are no longer necessary. | ||
TrieNode _delete(TrieNode node, List<V> value) { | ||
if (value.isEmpty) { | ||
// In case trie is empty and an empty value is passed. | ||
if (node == null) return null; | ||
|
||
node.isValue = false; | ||
|
||
// Checks all the children. If null, then deletes the node. | ||
var allNull = true; | ||
for (var child in node.children) { | ||
if (child != null) { | ||
allNull = false; | ||
break; | ||
} | ||
} | ||
return allNull ? null : node; | ||
} | ||
|
||
// In case trie is empty and some value is passed. | ||
if (node == null) return null; | ||
|
||
var path = _indexOf(value.first); | ||
value = value.sublist(1); | ||
|
||
// Path to value doesn't exist. | ||
if (node.children[path] == null) { | ||
return node; | ||
} | ||
|
||
node.children[path] = _delete(node.children[path], value); | ||
|
||
// Delete node if all children are null. | ||
if (node.children[path] == null) { | ||
var allNull = true; | ||
for (var child in node.children) { | ||
if (child != null) { | ||
allNull = false; | ||
break; | ||
} | ||
} | ||
return allNull ? null : node; | ||
} | ||
|
||
return node; | ||
} | ||
|
||
/// Returns index, which represents the [component] in `node.children`. | ||
int _indexOf(V component) => _components.indexOf(component); | ||
|
||
List _split(V value) { | ||
List<V> list = splitter(value); | ||
for (var component in list) { | ||
// TODO: Implement an error class instead. | ||
if (!components.contains(component)) throw ('$component ∉ $components'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Try throwing an error object instead, easily shareable and testable. |
||
} | ||
return list; | ||
} | ||
} | ||
|
||
/// Node of the trie, has connection to the set of components as [children]. | ||
class TrieNode<V extends Comparable> { | ||
/// If this node represents a value in the trie. | ||
bool isValue = false; | ||
|
||
/// Connection to [children]. | ||
List<TrieNode> children; | ||
|
||
/// Initializes the node to have as many [children] | ||
/// as there are components in the trie. | ||
TrieNode(Set components) { | ||
children = List<TrieNode>(components.length); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import 'package:test/test.dart'; | ||
import 'package:algorithms/trie/trie.dart'; | ||
|
||
void main() { | ||
Trie emptyTrie, trie, customTrie; | ||
|
||
setUp(() { | ||
emptyTrie = Trie.ofAlphabets(); | ||
|
||
trie = Trie.ofAlphabets(); | ||
trie.add('algorithms'); | ||
|
||
customTrie = Trie( | ||
{'a', 'b', 'f', 'o', 'r', 'z'}, (value) => value.toString().split('')); | ||
customTrie.add('foo'); | ||
}); | ||
|
||
test('Components', () { | ||
expect(trie.components, | ||
equals({...List.generate(26, (i) => String.fromCharCode(122 - i))})); | ||
|
||
expect(customTrie.components, equals({'f', 'o', 'b', 'a', 'r', 'z'})); | ||
}); | ||
|
||
test('Empty trie', () { | ||
expect(emptyTrie.isEmpty, isTrue); | ||
expect(trie.isEmpty, isFalse); | ||
}); | ||
|
||
test('Add value', () { | ||
trie.add('hi'); | ||
expect(trie.root.children[7].children[8].isValue, isTrue); | ||
|
||
customTrie.add('bar'); | ||
expect(customTrie.root.children[1].children[0].children[4].isValue, isTrue); | ||
|
||
customTrie.add('baz'); | ||
expect(customTrie.root.children[1].children[0].children[5].isValue, isTrue); | ||
}); | ||
|
||
test('Contains value', () { | ||
expect(emptyTrie.contains('test'), isFalse); | ||
|
||
expect(trie.contains('algorithm'), isFalse); | ||
expect(trie.contains('algorithms'), isTrue); | ||
|
||
expect(customTrie.contains('boar'), isFalse); | ||
expect(customTrie.contains('foo'), isTrue); | ||
}); | ||
|
||
test('Delete value', () { | ||
emptyTrie.delete(''); | ||
emptyTrie.delete('test'); | ||
|
||
expect(trie.contains('algorithms'), isTrue); | ||
trie.delete('algorithms'); | ||
expect(trie.contains('algorithms'), isFalse); | ||
|
||
expect(customTrie.contains('foo'), isTrue); | ||
customTrie.delete('foo'); | ||
expect(customTrie.contains('foo'), isFalse); | ||
}); | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.