Say I have a number of sets of words such as: (water, flour, eggs) and (beans, water, milk)
If a user enters a string that contains all those words in any order, a message is displayed. Such as "I have eggs water and some flour" -> "That makes a cake".
What is the most efficient way to accomplish this, assuming there may be a large number of word set and message combinations to check, for each string the user enters.
My initial idea is to use .contains:
for(each-word-set)
{
i = word-set.length;
for(each-word)
{
if(string.contains(word))
{
j++
}
}
if(i == j)
{
//Yes this string contains all words.
}
}
Is there a better method than this?
My initial way: Using the space as a delimiter.
We can do the following.
Create a List. As follows
1) Use Java split function. To create array.
List<String> list = new ArrayList<String>(Arrays.asList(string.split(" ")))`;
2) Create a Hash Map.
Map<String, String> hash = new HashMap<String, String>();
for(i = 0 ; i < list.length(); i++)
{
hash.put(list[i], list[i]);
}
Where the list[i]
is going to be your key.
3) Retrieve matches.
Now when the user enters a word you are interested in, you can use the containsKey
command. For example
if (hash.containsKey("flour") && hash.containsKey("water") && hash.containsKey("beans");
println("Whatever you want");
The thing to note is creating a HashTable is useful for big data sets. Here is a link, you should see to see the benefits. Retrieving data from a Hash Table is O(1), so virtually instantaneous.
Hopefully that was helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With