How do I consider a space character in a trie?
For example, I want to insert "a few" in the trie, but I do not know how to do it:
public void insertWord(String wordName){
for (int i = 0; i < wordName.length(); i++){
if( current.children[wordName.charAt(i) - 'a'] == null)
current.children[wordName.charAt(i) - 'a'] = new Node(wordName.charAt(i));
current = current.children[wordName.charAt(i) - 'a'];
}
}
I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -65 out of bounds for length 29
The length of array is equal to 29.
How can I solve this?
1 answer
-
answered 2022-01-25 18:32
trincot
The problem is that you define the index for the
children
array with the expressionwordName.charAt(i) - 'a'
. But the ordinal value of a space is much smaller than that of'a'
, so that becomes a negative value.Instead, you could define the conversion from character to index with the help of a constant string:
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz ";
Notice the space after the
z
. You could add more characters, if you want to support other characters like a comma, a point, ... capital letters, ...etc. But, the length of this string should not be greater than the length of thechildren
array.Then, in your function, you can use that string as follows:
int key = ALPHABET.indexOf(wordName.charAt(i)); if( current.children[key] == null) current.children[key] = new Node(wordName.charAt(i)); current = current.children[key];
do you know?
how many words do you know
See also questions close to this topic
-
Read each name in Array list to create seperate object for
I have a file that has student names, age, and an id number. I have a student class that holds the everything above for each student object. I stored all the names, id numbers. and age separately in an array list. Now im trying to assign the info to create a student object.
public class Student { private String lName; private int idNumber; private int age; public Student() { lName = ""; idNumber = 0; age = 0; } public Student(String l, int i, int a) { lName = l; idNumber = i; age = a; } public void setName(String last) { lName = last; } public String getName() { return lName; } public void setIdNum(int num) { idNumber = num; } public int getIdNum() { return idNumber; } public void setAge(int a) { age = a; } public int getAge() { return age; } }
My Text File looks something like this: This info is stored in parallel array lists. I don't quite get how to implement this into an object to pass it into my second contractor method.
Josh 2134 19 Smith 5256 21 Rogers 9248 19 Andrew 7742 20
Here's what I've tried;
public static void main(String[] args) { String file = "studentData.txt"; Scanner reader = new Scanner(file); ArrayList<String> lastNames = lNames(file); ArrayList<Integer> idNumbers = idNum(file); ArrayList<Integer> ageList = ages(file); Scanner input = new Scanner(System.in); Student s1 = new Student(); // confused about how to implement this constructor with the textile info for (int i = 0; i<idNumbers.size(); i++) { Student user = new Student(lastNames.get(i), idNumbers.get(i), ageList.get(i)); } //user enters idNumber to display age System.out.println("Enter ID Number"); //exception handling to be added int idNum = input.nextInt(); for (int i = 0; i<idNumbers.size(); i++) { if (idNum == idNumbers.get(i)) { s1.setAge(ageList.get(i)); System.out.println(s1.getAge()); } } }
-
Using EdittextPreference for Goto search
sorry for my poor English. I want to use EditTextPreference in my bottom nav like the pic below, ![screenshot][1]
I have recycleview xml in my project with in many sub cardview layouts(which is scrollable) and I want to create item in the bottom nav which is called "Goto". When the "Goto" item is clicked i want it to pop-up like the screenshot. And when user enters a number(according to the cardviews i.e if the number of cardview is 40 user must enter 1-40) I want to search the cardview by its ID. Thank you and I hope u got it, If u have any questions let me know [1]: https://i.stack.imgur.com/grK8P.jpg
My xml format look like this. As you see in the blow since the cardviews are huge in number it is not cool to scroll all the way down that is why i need Goto item in the bottom nav to search it by its ID when the user click number in the EditTextPreference as u see in the screenshot. i.e The screenshot is not from my app
<LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> .. .. .. .. many more..
-
How to get remaining time of the day in java?
I would like to calculate the time remaining for next day 00:00:00 from the current date time.
For e.g. time difference between 2
022-05-07T05:49:41.883807900Z
and2022-05-08T00:00:00Z
Expected answer:
18:10:19
or 65419 (in seconds).How can I achieve this with efficiently using java 8?
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
VBA: Creating a class property that is an array of dictionaries
In Microsoft Excel VBA I need to create a class that has two properties, "Name" and "Holdings". "Name" is just a string so the code for that is easy. But I need "Holdings" to be a variable length array containing dictionary objects. So this is what I wrote:
Private mName As String Private mHoldings() As Scripting.Dictionary Public Property Let Name(vName As String) mName = vName End Property Public Property Get Name() As String Name = mName End Property Public Property Set Holdings(vHoldings() As Scripting.Dictionary) Set mHoldings = vHoldings End Property Public Property Get Holdings() As Scripting.Dictionary Set Holdings = mHoldings End Property
When I try to compile it gives me this error: "Definitions of property procedures for the same property are inconsistent, or property procedure has an optional parameter, a ParamArray, or an invalide Set final parameter.
What I doing wrong?
-
Map for react-native ( No google map and apple map)
Is there a map that can be used in React-Native?
If so, please upload an example of how to use it.
But again! No Google map and Apple map.
-
I was trying to implement a dictionary using trie data structure but the insertWord function is not working properly
What my main doubt is that whenever I try passing the root node as a default value in the
insertWord
function it throws a compilation error. I do not know where I am going wrong. If somebody could help me. Thank you.#include <iostream> #include <string> using namespace std; class TrieNode { public: char data; TrieNode** children; bool isTerminal; TrieNode(char data) { this->data = data; children = new TrieNode*[26]; for (int i = 0; i < 26; i++) { children[i] = NULL; } isTerminal = false; } ~TrieNode() { for (int i = 0; i < 26; i++) { delete children[i]; } } }; class Trie { private: TrieNode* root; Trie() { root = new TrieNode('\0'); } void insertWord(string word, TrieNode* node = root) {} }; int main() { cout << "Hello World"; return 0; }
-
Trie search tree vs ternary search tree for autocomplete?
I'm trying to implement a datastructure such that it'll give autocompleted words when the user writes something. So far I've implemented a trie properly, and the autocomplete works quite fast. Thing is, when loading all the information needed, it uses a bonkers amount of memory. I've generally seen that many people say that tries are faster but less space efficient, and vice versa for a ternary tree. I've got an alphabet of about 55-60 characters and am expecting about 800k - 1.2 million words inserted into the tree. Is this just generally a way too large amount of insertions into the trie to work well, space wise? Would switching it to a ternary tree be smarter, memory wise? And would it, if switched to a ternary tree, be "annoyingly" slow to search in?
Thanks!
-
Access Violation Error in Trie of Wordsearch Solver
I'm currently building a wordsearch solver using a trie data structure for the dictionary, my problem is when I use it to search for words in my 2D array wordsearch grid I often get an error saying:
Unhandled exception at 0x00007FF72A169BD4 in ACW_WordSearch.exe: 0xC0000005: Access violation reading location 0x000001CD4134DF10.
I think it may be due to the function getting overused as it is used to check every word sequence in the grid.
Can anyone help me to make either my solver function or my search function more efficent so it wont break.
Here is the necessary code:
Wordsearch.cpp
void WordSearch::readSimpleDictionary() { ifstream fileIn(dictionaryName); while (getline(fileIn, word)) { words.push_back(word); } } void WordSearch::readAdvancedDictionary() { ifstream fileIn(dictionaryName); while (getline(fileIn, word)) { insertWord(word, root); searchWord(word, root) ? cout << "Yes\n" : cout << "No\n"; } } void WordSearch::solvePuzzleAdvanced() { for (int i = 0; i < row; i++) { for (int k = 0; k < column; k++) { string b = ""; for (int j = 0; j < column - k; j++) { b.push_back(grid[i][j + k]); if (searchWord(b, root) == true) { advancedwordsFound.push_back(b); } else { } } } } for (int i = 0; i < row; i++) { for (int k = 0; k < column; k++) { string b = ""; for (int j = 0; j < column - k; j++) { b.push_back(grid[j + k][i]); if (searchWord(b, root) == true) { advancedwordsFound.push_back(b); } else { } } } for (int i = 0; i < row; i++) { for (int k = 0; k < column; k++) { string b = ""; for (int j = column - 1; j > 0; j--) { b.push_back(grid[i][j - k + 1]); if (searchWord(b, root) == true) { advancedwordsFound.push_back(b); } else { } } } } for (int i = 0; i < row; i++) { for (int k = 0; k < column; k++) { string b = ""; for (int j = column - 1; j > 0; j--) { b.push_back(grid[j - k][i]); if (searchWord(b, root) == true) { advancedwordsFound.push_back(b); } else { } } } } std::cout << "Function not implemented" << std::endl; } }
Dictionary.h
#include <string>; #include <vector>; #include <iostream>; #include <cassert> #pragma once using namespace std; struct Trie { struct Trie* children[26]; bool isEndOfWord; }; inline struct Trie* getNode(void){ struct Trie* node = new Trie; node->isEndOfWord = false; int i = 0; while (i < 26) { node->children[i] = NULL; i++; } return node; } inline bool searchWord(string currentWord, struct Trie* root) { struct Trie* current = root; int i = 0; while (i < currentWord.length()){ int index = currentWord[i] - 'A'; if (current->children[index] == NULL) { return false; } current = current->children[index]; i++; } return (current->isEndOfWord); } inline void insertWord(string currentWord, struct Trie* root) { struct Trie* current = root; int i = 0; while(i < currentWord.length()){ int index = currentWord[i] - 'A'; if (current->children[index] == NULL) { current->children[index] = getNode(); } current = current->children[index]; i++; } current->isEndOfWord = true; }