I have been going through the Java interview questions asked by my company and came across one that I can't seem to find the solution.
Here is the question:
Please write a method (function) accepting as single parameter a
string and reversing the order of the words in this string.
The " " is the word separator and any other char is considered as being part of a word. In order to simplify, please consider that there is always one space between the words.
Important - You are NOT allowed to use other strings or arrays or other data structures containing several elements - just plain atomic variables such as integers, chars etc.
Also, it is not allowed to use any other language specific string function other than the function giving you the length of the string.
Expected result:
"hello my beautiful world" -> "world beautiful my hello"
So, I can't use: chars[], str.split(), str.charAt(), str.substring(), StringBuilder, another declaration of String.
Should I use recursion to do it?
Since, String is Immutable and uses encapsulation,
There is no solution to your problem. You can't update the values directly, no setters are available and without the access to the getters (since you can only use .length), you can't read the value.
So, I would suggest to respond that Immutability and encapsulation prevent you from doing so.
In real life as a software engineer, you'll sometimes be asked to do things that are technically impossible or even nonsensical. Sometimes the person asking will be someone important like your boss or a big customer.
If someone actually asks you this interview question, then you're in one of those situations. That makes this question pretty interesting, and you might want to figure out what the best way to answer really is.
If someone asked me, this is how I would answer, and as an interviewer, this is the kind of answer I would award the most points for:
1) Explain how it's technically impossible to meet the requirements, but do it without making me feel stupid. This shows diplomacy.
2) Figure out what I really want. In this case, the interviewer probably wants to see if you know how to reverse the words in a string using low-level operations. This is a perfectly reasonable C language question, for example. Figuring out what the interviewer really wants shows experience and judgement.
3) Provide an answer that gives me what I want. Write this method in Java, but take a StringBuilder instead of a string, and call only length(), charAt(), and setCharAt(). This shows the expertise that the interviewer wants to see.
Related
Eg:
I have given a string like : "I am going to school now, I am going to school now"
The requirement is changing I -> We & am -> are so that the output looks like "We are going to school now, We are going to school now"
which mean i have to replace some pattern of string to the other.
What is best to to accomplish this in Java
Dealing with strings is always bad in terms of memory efficiency, as you can't change a string, only create new ones.
The best thing would be to receive a StringBuilder (StringBuffer if you need to be ThreadSafe) and then use some algorithm to change the string or something like this:
http://www.java-examples.com/java-stringbuffer-replace-example
However, if you receive a string itself, I would just use the replaceAll method to create a new string, as you would need to do it anyway, even with a string buffer:
http://www.roseindia.net/java/string-examples/string-replaceall.shtml
If you need to do several subsequent changes in a string, though, it always pay the way to convert to a stringbuffer first.
It depends on what you are trying to do.
If you simply want to replace all occurrences of "I" with "We" and "am" with "are", then String.replace is going to be more memory efficient than String.replaceAll.
If you want to treat "I" and "am" as words rather than as character sequences, then String.replace won't work. Instead you need to use String.replaceAll with a pattern that uses word boundary matches to avoid turning (for example) "I am going to school on a camel" into "We are going to school on a careel".
In both cases, you should be able to get better memory efficiency (i.e. less generation of garbage) by doing the work by hand using a StringBuilder and a loop to iterate over the characters of the original string and build the new one.
HOWEVER ... coding like that is painful, and not the sort of thing you should consider doing, unless you have convincing evidence that you need to do it. Premature optimization is a bad idea. 99.9% of the time, it really doesn't matter if you create slightly more garbage than an is theoretically necessary.
That depends of your app. This could be as simple as the other posters showed, or it is complex and is an own part of computer science. In the later case, a so called "trie" is build. That works like a tree but have syllables in each node.
Navigation systems use that, to memory effeciently store the name of the street names of all streets of a country.
Now this is a tricky problem for which I'm not able to figure out a good solution. Suppose we have a String in Java:- "He ate 3 apples today." Now the digit 3 can be easily identified in Java using isNumeric function or using regular expressions. But what if I have a String like: "He ate three apples today."? How can I identify that three is actually a number? I used OpenNlp and used its POS tagger but the time it takes to do is really too much! Can anyone suggest a better solution for this? Also among the ".bin" of OpenNlp, there is one file-"num.bin", but I don't know how to use this file. OpenNlp documentation also say nothing about it. Can anyone tell me if this is exactly what I've been looking for, and if yes then how to use it.
/*********************************************************************************************************************************/
I'm actually short of time here, so I've settled on a temporary solution here. Make a file/dictionary and take all the entries in a hashtable. Then I'll tokenize my sentence and check word by word for numbers, similar to what you guys suggested. I'll keep on updating the file as and when required. Thanks for your valuable suggestions guys, and if you have got something better than this I'd be really glad. OpenNlp implements this in a very good way, the only problem with it is time complexity and I want to do this in minimum time possible.
Create a dictionary of numbers. Search for elements from that dictionary in the text.
Check asympotic complexity, it may be cheaper to sort the text first.
You have to keep all that words in arrays and then use it. Here is an example how to convert number to string. It may help you... I think you have to split your text into words and check if a word is a number (three). If yes check the next word because it can be say "million", then check the next word and so on. It's not easy and seems like a little library.I think you'll spend a lot of time writing this. Or try to search in google for a library like this. Maybe someone have already got this problem, wrote a library and shares it for free )) Good luck.
I am currently working on a project where I need to create possible answers to WH question based on a given sentence.
Example sentence is:
Anna went to the store.
I need to create possible answers to the following questions.
Who went to the store?
Where did ana go?
I had already implemented the POST-Tagging of the words and I now know the Part of Speech of the word.
I had difficulty on determining what type of noun is the word if it is a noun so I can create a template for my answer.
Example is:
Anna - noun - person: possible answer to question who.
Store - noun - place: possible answer to question where.
I want to implement this using java
You should not try to infer possible questions and their answers from the nouns present in a sentence. Instead, you should infer the type of questions you can ask from the activity described by the verb. In your example, the system should infer that the activity of going requires a subject who goes (possible answer to the "who" question), a place where the subject goes (possible answer to the "where to" question) as well as the time when the subject went there (possible answer to the "when" question) and potentially more (from where? with whom? by what means? which way? etc). Then it should check which answers are provided in the question. In your example, answers to "who" and "where" are provided, but "when" is not. In other words, you should have a mapping from verbs to questions that make sense for each verb.
Then for each question applicable to the verb you should store prepositions that are used to indicate that answer in a sentence. For example, the answer to the "where to" question is often preceded by "to" and an answer to "when" question is often preceded by "at" or "on". Note that subject (here answer to the "who" question) needs special treatment. Also, some verbs can be immediately followed by an object without prepositions and your verb dataset should indicate the question to which they constitute an answer. For example the verb "to enter" can be followed by an object which answer the "where/what" question as in "Anna entered the room". Also, some nouns are exceptions and are never preceded by a preposition. For example "home" as in "Anna went home". You need to treat these specially as well. Another thing to watch out for are idiomatic expressions like "Anna went to great lengths". Again, special treatment is required.
Generally, nouns in English do not have enough structure to allow you to determine what type of thing (e.g. a place, an object, a person, a concept etc) they denote. You would need to have a large dataset that breaks up all the words known to the system into different categories. If you do use a noun set like this, it should have a supporting role to increase system's accuracy.
Relying on verbs and prepositions is far more flexible as it allows the system to handle unknown expressions. For example, someone might say "Anna went to Bob", but "Bob" is not a place. System that infers the role of each element from verb and preposition still handles this situation and properly treats "Bob" as the right answer for the "where to" question.
I will be focusing only on your problem in determining the noun types instead of the approach for answering factoid questions.
SuperSense Tagger is one resource/tool that provides a more specific type/sense information for a POS. You can check the token categories which include noun:person and noun:location. There are wrappers for Java (you can just search for them).
The following list contains 1 correct word called "disastrous" and other incorrect words which sound like the correct word?
A. disastrus
B. disasstrous
C. desastrous
D. desastrus
E. disastrous
F. disasstrous
Is it possible to automate generation of wrong choices given a correct word, through some kind of java dictionary API?
No, there is nothing related in java API. You can make a simple algorithm which will do the job.
Just make up some rules about letters permutations and doubling and add generated words to the Set until you get enough words.
There are a number of algorithms for matching words by sound - 'soundex' is the one that springs to mind, but I remember uncovering a few when I did some research on this a couple of years ago. I expect the problem you would find is that they take a word and return a value that represents how the word sounds so you can see if two spellings sound similar (so the words in the question should generate similar values); but I expect doing the reverse, i.e. taking the value and generating similar sounding spellings, would be quite hard.
I worked the last 5 days to understand how unification algorithm works in Prolog .
Now ,I want to implement such algorithm in Java ..
I thought maybe best way is to manipulate the string and decompose its parts using some datastructure such as Stacks ..
to make it clear :
suppose user inputs is:
a(X,c(d,X)) = a(2,c(d,Y)).
I already take it as one string and split it into two strings (Expression1 and 2 ).
now, how can I know if the next char(s) is Variable or constants or etc.. ,
I can do it by nested if but it seems to me not good solution ..
I tried to use inheritance but the problem still ( how can I know the type of chars being read ?)
First you need to parse the inputs and build expression trees. Then apply Milner's unification algorithm (or some other unification algorithm) to figure out the mapping of variables to constants and expressions.
A really good description of Milner's algorithm may be found in the Dragon Book: "Compilers: Principles, Techniques and Tools" by Aho, Sethi and Ullman. (Milners algorithm can also cope with unification of cyclic graphs, and the Dragon Book presents it as a way to do type inference). By the sounds of it, you could benefit from learning a bit about parsing ... which is also covered by the Dragon Book.
EDIT: Other answers have suggested using a parser generator; e.g. ANTLR. That's good advice, but (judging from your example) your grammar is so simple that you could also get by with using StringTokenizer and a hand-written recursive descent parser. In fact, if you've got the time (and inclination) it is worth implementing the parser both ways as a learning exercise.
It sounds like this problem is more to do with parsing than unification specifically. Using something like ANTLR might help in terms of turning the original string into some kind of tree structure.
(It's not quite clear what you mean by "do it by nested", but if you mean that you're doing something like trying to read an expression, and recursing when meeting each "(", then that's actually one of the right ways to do it -- this is at heart what the code that ANTLR generates for you will do.)
If you are more interested in the mechanics of unifying things than you are in parsing, then one perfectly good way to do this is to construct the internal representation in code directly, and put off the parsing aspect for now. This can get a bit annoying during development, as your Prolog-style statements are now a rather verbose set of Java statements, but it lets you focus on one problem at a time, which is usually helpful.
(If you structure things this way, this should make it straightforward to insert a proper parser later, that will produce the same sort of tree as you have until then been constructing by hand. This will let you attack the two problems separately in a reasonably neat fashion.)
Before you get to do the semantics of the language, you have to convert the text into a form that's easy to operate on. This process is called parsing and the semantic representation is called an abstract syntax tree (AST).
A simple recursive descent parser for Prolog might be hand written, but it's more common to use a parser toolkit such as Rats! or Antlr
In an AST for Prolog, you might have classes for Term, and CompoundTerm, Variable, and Atom are all Terms. Polymorphism allows the arguments to a compound term to be any Term.
Your unification algorithm then becomes unifying the name of any compound term, and recursively unifying the value of each argument of corresponding compound terms.