So this is the continuation of my question from this thread: here
String[] words = {"cowboy", "animal", "monster"};
String[] meanings = {"meaning1", "meaning2", "meaning3"};
boolean check = false;
for (int i = 0; i < words.length; i++) {
if (s.toLowerCase().contains(words[i].toLowerCase())) {
check = true;
} else {
}
}
if (check) {
System.out.println("Yes");
} else {
System.out.println("No");
}
But I can't seem to figure out how and where to put the specific meaning of each word that has been typed by the user in the edittext. Any help would be gladly appreciated. Thanks.
static String[] words = { "Cowboy", "animal", "monster" };
static String s = "My animal is a Cowboy";
static boolean check = false;
static String[] meanings = {"meaning1", "meaning2", "meaning3"};
static ArrayList<String> typed_words = new ArrayList<String>();
static ArrayList<String> typed_meanings = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
if (s.toLowerCase().contains(words[i].toLowerCase())) {
typed_words.add(words[i]);
typed_meanings.add(meanings[i]);
check = true;
} else {
}
}
if (check) {
System.out.println("Yes");
for(int i=0;i<typed_words.size();i++){
System.out.println("Word: "+typed_words.get(i)+" Meaning: "+typed_meanings.get(i));
}
} else {
System.out.println("No");
}
what about something like that?
int index;
...
if (s.toLowerCase().contains(words[i].toLowerCase())) {
check = true;
index = i;
} else {
....
if (check) {
System.out.println(meanings[index]);
} else {
...
If the words and their meanings have the same relative positions in the two arrays then re-use the index i to print the corresponding meaning as well. But, the i would now have to be defined outside the loop so that it has a bigger scope now and is available inside the if check.
int i = 0
for (; i < words.length; i++) {
if (s.toLowerCase().contains(words[i].toLowerCase())) {
check = true;
break;
}
}
if (check) {
System.out.println("Meaning found: " + meanings[i]);
}
Since words and meanings arrays have the relative indexing, you can-
boolean check = false;
for (int i = 0; i < words.length; i++) {
if (s.equalsIgnoreCase(words[i])) { // We don't need "toLowerCase"
System.out.println("Word: " + words[i] + "\tMeaning: " + meanings[i]);
check = true;
break; // Match found; so get out of the loop
}
}
if(check){
System.out.println("Found!");
} else {
System.out.println("Not Found!");
}
Why not use a java.util.HashMapin which every word maps to a meaning?
String s = "";
HashMap<String,String> meaningMap = new HashMap<String,String>();
//just for the example
meaningMap.put("cowboy", "meaning1");
...
if (s.toLowerCase().contains(words[i].toLowerCase())) {
ouput = meaningMap.get(s);
}
...
System.out.println(s);
Another idea would be to use HashMap to store your data.
HashMap hm = new HashMap();
hm.put("cowboy", "meaning1");
hm.put("animal", "meaning2");
And then use
String s = yourEdittext.getText();
String[] words = s.split("\s+");
for (int i = 0; i < words.length(); i++) {
words[i] = words[i].replaceAll("[^\w]", "");
}
for (int i=0; i < words.length(); i++) {
if (hm.containsKey(words[i])) {
System.out.println("Meaning found: " + hm.get(words[i]));
}
}
This basically gets the sentece form the edittext, splits it into words then checks if each word is in the HashMap. This is good if your list of words is going to be quite big in comparison to the length of the sentence.
i would suggest that you make a Hashmap<String ,ArrayList<String>>
as you have more than one meaning for oneword.
so now just passing the word you need to find the meaning for.
you can.also use treemap if you need to store them in a sorted fashion.
so here's how you can find the meaning for a word .
ArrayList<String> meaning =map.get("cowboy");
for(String string : meaning ) {
Log.v("meaning",string);
}
Related
I have a string array for example:
new String[] = {"powerhouse", "p, pow, power, house, pose, poser"};
My goal is to split the first entry in the array in this case powerhouse into any two words and check them against the second entry, which serves as a dictionary of words.
Here's my implementation so far:
public static String[] convertWordsToArray(String input){
String[] wordArr = null;
wordArr = input.split(",");
return wordArr;
}
public static String splitEm(String[] strArr) {
String fw = strArr[0];
String sw = strArr[1];
String[] arrOne = convertWordsToArray(fw);
System.out.println(arrOne.length);
String[] dict = convertWordsToArray(sw);
System.out.println(dict.length);
for(int i = 0; i < dict.length - 1; i++) {
String mWord = fw.split(i, i + 1);
System.out.println(mWord);
}
// Edit Starts Here, tried to substring it but nothing prints in log
for(int i = 0; i < arrOne.length; i++) {
String mWord = fw.substring(0, i);
System.out.println(mWord);
}
return ""; // empty for now
}
I am stuck at the part where the first word has to be split. Should I use two loops, one for the first word and the other for the dictionary? I know that somehow the dictionary has to be converted to a list or array list to avail the .contains() method. How do I go about this? Thanks.
If anyone want the solution for PHP language, then you can use below code:
function ArrayChallenge($strArr) {
$dictWords = explode( ',', $strArr[1] );
$strLength = strlen($strArr[0]);
$output = 'not possible';
for( $i = 1; $i < $strLength; $i++ ){
$firstStr = substr($strArr[0], 0, $i);
$lastStr = substr($strArr[0], $i, $strLength);
if ( in_array( $firstStr, $dictWords ) && in_array( $lastStr, $dictWords ) ) {
$output = $firstStr . ',' . $lastStr;
break;
}
}
return $output;
}
Do you need something like this?
String s = "powerhouse";
List<String> list = new ArrayList<String>();
for(int i = 0; i < s.length(); i++){
for(int j = i+1; j <= s.length(); j++){
list.add(s.substring(i,j));
}
}
System.out.println(list);
I assume you need something like below:
Split second string at each , or even better using regex to trim
spaces before or after ,
check if each part of the splited entry fro above point is made of
only the chars contained in the first entry of your input
example
public static void main(String args[]) {
String[] test1 = {"powerhouse", "p, pow, power, house, pose, poser"};
String[] test2 = {"powerhouse", "p, xyz, power, house, pose, poser"};
System.out.println(check(test1));
System.out.println(check(test2));
}
static boolean check(String[] input){
String firstEntry = input[0];
String[] dictionary = input[1].split("\\s*,\\s*");
for(int i = 0; i < dictionary.length; i++){
if(!dictionary[i].matches("["+firstEntry+"]+")){
return false;
}
}
return true;
}
this will print true for the first case and false for the second as "xyz" is not a valid subpart/substring according to your discription
Try this :
public class Stack {
public static void main(String[] args) {
String[] str = {"powerhouse", "p, pow, power, house, pose, poser"};
String firstPart = str[0];
String secondPart = str[1];
boolean contain = isContain(firstPart, secondPart);
System.out.println(contain);
}
private static boolean isContain(String firstPart, String secondPart) {
for (int i = 0; i < firstPart.length(); i++) {
String firstWord = firstPart.substring(0, i);
String secondWord = firstPart.substring(i, firstPart.length());
List<String> strings = Arrays.asList(secondPart.trim().split("\\s*,\\s*"));
if (strings.contains(firstWord) && strings.contains(secondWord)) return true; if you want to check both words use this
//if (strings.contains(firstWord) || strings.contains(secondWord)) return true; if you want to check any(one) word from two words use this
}
return false;
}
}
My goal is to print out names with 2 letters that are the same with only one of the same letter in the name. For example brook would be printed out as brok and michelle would be printed out as michel. Whats wrong with my code?
for(int a = 0; a < word_1.length(); a++)
{
mychar = word_1.charAt(a);
for(int c = 1; c <word_1.length(); c++)
{
mychar_2 = word_1.charAt(c);
if(mychar == mychar_2)
{
word_3 = word_3 + "";
}
else
{
word_3 = word_3 + mychar;
}
}
}
System.out.println(word_3);
Better question is "what is right with the code". Basically the idea looks like going through all letters and then going through all matches. This is not too bad and we can slightly change your code to make it work (see comments):
for(int a = 0; a < word_1.length(); a++)
{
char mychar = word_1.charAt(a);
// flag for matching letters
Boolean found = false;
// you go through only previous characters!
for(int c = 0; !found && c < a; c++)
{
char mychar_2 = word_1.charAt(c);
if(mychar == mychar_2)
{
found = true;
}
}
// here you add character if no match found
if(!found) {
word_3 = word_3 + mychar;
}
}
This is a good way in academic coding, but in actual project if you deal with large numbers of words, you have to consider Map based solution to keep all existing letters and iterate only once through each word. Or you can search for some methods in numerous java libraries to do the job
This would solve the problem:
String testWord = "brook";
List<String> testSet = new ArrayList<String>();
for (int i = 0; i < testWord.length(); i++) {
if (!testSet.contains(String.valueOf(testWord.charAt(i)))) {
testSet.add(String.valueOf(testWord.charAt(i)));
}
}
StringBuilder builder = new StringBuilder();
for (Object s : testSet.toArray()) {
builder.append((String) s);
}
String str = builder.toString();
System.out.println(str);
Given two List sentence and List queries
I have two find the occurrence of queries in sentences.
Example,
"Pulkit likes StackOverflow and coding"
"Pulkit does not like Reddit"
"Pulkit like ice cream"
Queries
Pulkit coding
like
does
The function should return for the queries
sentence[0]
sentence[1], sentence[2]
sentence[1]
I solved this question already using HashMap but it is quadratic and I am wondering how to do it in linear time.
Solution
public static void findMatch(List<String> sentences, List<String> queries) {
// Write your code here
// Split the sentences into terms and map them by index
Map<Integer, Set<String>> sentencesSplit = new HashMap<>();
for (int j = 0; j < sentences.size(); j++) {
String[] splitSentence = sentences.get(j).split(" ");
Set<String> sentenceSet = new HashSet<>();
sentencesSplit.put(j, sentenceSet);
for (int i = 0; i < splitSentence.length; i++) {
sentenceSet.add(splitSentence[i]);
}
}
// Split the query into terms and map them by index
Map<Integer, String[]> queriesSplit = new HashMap<>();
for (int i = 0; i < queries.size(); i++) {
queriesSplit.put(i, queries.get(i).split(" "));
}
for (int i = 0; i < queries.size(); i++) {
String found = null;
for (int j = 0; j < sentences.size(); j++) {
String[] splitQuery = queriesSplit.get(i);
Set<String> sentenceStringList = sentencesSplit.get(j);
boolean notFound = false;
for (int k = 0; k < splitQuery.length; k++) {
if (!sentenceStringList.contains(splitQuery[k])) {
notFound = true;
break;
}
}
if (!notFound) {
if (found == null) {
found = "" + j;
} else {
found += " " + j;
}
}
}
if (found == null) {
found = "-1";
}
System.out.println(found);
}
}
My code is similar with human's thinking.
\b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b.
Hope my code will help you.
public class MainClass {
public static void main(String [] args)
{
List<String> sentences = new ArrayList<String>();
sentences.add("Pulkit likes StackOverflow and coding");
sentences.add("Pulkit does not like Reddit");
sentences.add("Pulkit like ice cream");
List<String> queries = new ArrayList<String>();
queries.add("Pulkit coding");
queries.add("like");
queries.add("does");
findMatch(sentences, queries);
}
public static void findMatch(List<String> sentences, List<String> queries) {
for(String query : queries) {
System.out.print("]");
String match = ".*\\b" + query.replace(" ", "\\b.*") + "\\b.*";
for (int iSentence = 0; iSentence < sentences.size(); iSentence++) {
if(sentences.get(iSentence).matches(match)) {
System.out.print(" " + iSentence);
}
}
System.out.println("");
}
}
}
Console output:
] 0
] 1 2
] 1
As the title says, I'm working on a project in which I'm searching a given text, moby dick in this case, for a key word. However instead of the word being linear, we are trying to find it via a skip distance ( instead of cat, looking for c---a---t).
I've tried multiple ways, yet can't seem to get it to actually finish one skip distance, have it not work, and call the next allowed distance (incrementing by 1 until a preset limit is reached)
The following is the current method in which this search is done, perhaps this is just something silly that I'm missing?
private int[] search()
throws IOException
{
/*
tlength is the text file length,
plength is the length of the
pattern word (cat in the original post),
text[] is a character array of the text file.
*/
int i=0, j;
int match[] = new int[2];
int skipDist = 2;
while(skipDist <= 100)
{
while(i<=tlength-(plength * skipDist))
{
j=plength-1;
while(j>=0 && pattern[j]==text[i+(j * skipDist)])j--;
if (j<0)
{
match[0] = skipDist;
match[1] = i;
return match;
}
else
{
i++;
}
}
skipDist = skipDist + 1;
}
System.out.println("There was no match!");
System.exit(0);
return match;
}
I do not know about the method you posted, but you can use this instead. I've used string and char array for this:
public boolean checkString (String s)
{
char[] check = {'c','a','t'};
int skipDistance = 2;
for(int i = 0; i< (s.length() - (skipDistance*(check.length-1))); i++)
{
boolean checkValid = true;
for(int j = 0; j<check.length; j++)
{
if(!(s.charAt(i + (j*skipDistance))==check[j]))
{
checkValid = false;
}
}
if(checkValid)
return true;
}
return false;
}
Feed the pattern to match in the char array 'check'.
String "adecrayt" evaluates true. String "cat" evaluates false.
Hope this helps.
[This part was for fixed skip distance]
+++++++++++++++++++++++++++
Now for any skip distance between 2 and 100:
public boolean checkString (String s)
{
char[] check = {'c','a','t'};
int index = 0;
int[] arr = new int[check.length];
for(int i = 0; i< (s.length()); i++)
{
if(check[index]==s.charAt(i))
{
arr[index++] = i;
}
}
boolean flag = true;
if(index==(check.length))
{
for(int i = 0; i<arr.length-1; i++)
{
int skip = arr[i+1]-arr[i];
if(!((skip>2)&&(skip<100)))
{
flag = false;
}
else
{
System.out.println("Skip Distance : "+skip);
}
}
}
else
{
flag = false;
}
return flag;
}
If you pass in a String, you only need one line:
public static String search(String s, int skipDist) {
return s.replaceAll(".*(c.{2," + skipDist + "}a.{2," + skipDist + "}t)?.*", "$1");
}
If no match found, a blank will be returned.
I am trying to search an array for a couple of specific strings that I get from words in a sentence. Eventually this sentence will be in-putted by the user but I have hard coded it in at the moment to make testing easier.If the program finds the strings it should return with "Yes" and "No" if it doesn't. The problem is that I am getting yes all the Time.
public class main {
public static void main(String[]args)
{
String Sentence = "This is a sentence";
String[] CensorList =
{"big","head"};
String[] words = Sentence.split(" ");
System.out.println(words.length);
boolean match = false;
for(int i = 0; i < words.length; i++)
{
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].equals(CensorList[j]))
{
match = true;
}else{
match = false;
}
}
}
if (match = true){
System.out.println("Yes");}
else{
System.out.println("No");
}
}
}
I would really appreciate any help with this one, Thanks in advance.
the if in your second for() has wrong braces.
try this one:
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].equals (CensorList[j])) {
match = true;
System.out.println("Yes");
} else {
System.out.println("No");
}
match = false;
}
for your second try:
the
if (match = true)
does not compare match with true, it sets the match flag to true, which results always in true.
compare the flag in your if:
if (match == true) // or simply if (match)
{ ....
Try it:
for(int i = 0; i < words.length; i++)
{
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].equals (CensorList[j]))
match = true;
}
if (match) {
System.out.println("Yes"); }
else {
System.out.println("No"); }
match = false;
}
I think you have some typos in here.
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].equals (CensorList[j]));
}
This will do essentially nothing, as the if has nothing to do if the expression is evaluated to true. Then after the loop you set match to true, so it will be true always, and it will always print "Yes"
You can use a simple RegEx based solution for this
private static boolean test(String value) {
String[] CensorList = { "This", "No" };
for (String string : CensorList) {
Pattern pattern = Pattern.compile("\\b" + string + "\\b", Pattern.CASE_INSENSITIVE);
if (pattern.matcher(value).find()) {
return true;
}
}
return false;
}
Then
String string = "This is a sentence";
if(test(string)){
System.out.println("Censored");
}
Any reason you are not using String.indexOf(String) ?
Another issue is if you are doing this repeatedly for the same (very large) stirng in which case, you might want to look into more sophisticated algorithms like suffix trees or even use specialized software like Apache Lucene
Try to use
public class main {
public static void main(String[]args)
{
String Sentence = "This is a sentence";
String[] CensorList =
{"This","No"};
String[] words = Sentence.split(" ");
System.out.println(words.length);
boolean match = false;
for(int i = 0; i < words.length; i++)
{
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].compareTo(CensorList[j])==0)
{
System.out.println("Yes");
}
else{System.out.println("No");}
}
}
}