I have a Text Box in my app and the user can input anything. I am creating a controller which interprets some of the commands based on the keywords.
The user has an option of either setting a password or not. And depending on that, my interpreter will either expect a password or not.
For example, if a Password is set and user enters: "password1 show list".
The interpreter checks for password in the first word, then next for the command(show) and then the argument(list).
If password not set, user enters "show list" and the interpreter understands.
My current code is:
// 'words' is a String array which contains the user input.
if (passwordEnabled()==true) {
if (words[0].contentEquals(getPassword())
&& words[1].contentEquals("show")
&& words[2].contentEquals("list")) {
// Perform action
}
}
else {
if (words[0].contentEquals("show")
&& words[1].contentEquals("list")) {
// Perform action
}
}
My question is, is there a more efficient/better way to process commands? I am sure mine is a very crude method of doing it.
Your way (or any grammar-based approach) is OK if users can remember the syntax of the commands.
If you want to understand the users when they express their intent with unrestricted, natural language, you need to do some Natural Language Understanding.
Something like Wit (http://wit.ai) may do the job for you. It's based on machine learning. It converts free text sentences into JSON with the user intent and normalized parameters.
If you are trying to design the "language" based system, where you ask commands, you should think about two possible approaches based on the system complexity:
building the finite automa of your system. Your if statements are the very basic form of such structure, but definind this as an actual automa, where you have states, and commands that moves you to the another state - is a very clean and generic approach.
building a grammar + interpreter/compiler. Defining correct commands as grammatical (+compiler) rules would give you much more power in expressing possible commands and actions.
Of course these are not alternating solutions - building a grammar for the language is a very broad thing, and should be used to parse the command, while finite state automa serves as the internal memory and the definition of possible actions.
Building a grammar or finite automa are right ways of doing that, agreed.
If you want an easy way, you may simplify your code like that:
if (passwordEnabled()) {
if (! words.get(0).contentEquals(getPassword()))
{
// wrong password
return;
}
words.remove(0); // skip password
}
if (words.get(0).contentEquals("show")
&& words.get(1).contentEquals("list")) {
// Perform action
}
Suppose you use ArrayList for words.
Related
I'm looking for a flexible/generic way to build up conditions using metadata stored in a Database and then validate incoming requests at runtime
against the conditions and concatenate value(s) if the condition is met.
My use case looks something like this:
1) A business user selects an operation from a UI i.e. (IF condition from a dropdown), then selects an appropraite field to evaluate i.e. ("language")
then selects a value for the condition i.e. "Java" followed by some values to concatenate i.e "Java 9" and "is coming soon!"
2) This metaData will get stored in a Database (lets say as a List for the moment) i.e ["language","Java","Java 9","is coming soon"]
When my application starts I want to build the appropriate concatenation conditions:
private String concatenateString(String condition, String conditionValue, String concatValue1, String concatValue2){
StringBuilder sb = new StringBuilder();
if (condition.equals(conditionValue)){
sb.append(concatValue1);
sb.append(concatValue2);
}
return sb.toString();
}
3) so at runtime when I receieve a request, i want to compare the values on my incoming request to the various conditions that got built at start up:
if language == "Java" then the output would look like => "Java 9 is coming soon"
While the above might work for 2 String concatenations, how can achieve the same for a variable number of conditions and concatenation values.
So you want user to create a program by selecting options from a GUI which will be stored in a DB. When the options are read back from the DB you want to parse this into a compileable program and run it?
Use StringBuilder to build a string of the code from the data gotten back from the DB, something like this:
"if (language == '"Java"') { doSomething() }" (you'll need to take care to escape strings inside your string if you are storing strings in the DB.
You can then use Compiler class to compile the string to a program which yo can run (all in runtime, google dynamically compiling c# at runtime).
However, you'll probably want to question why you are thinking of going down that route... I've been there before, dynamic compilation has a very narrow use case.
You could, for instance, create a Dictionary which maps selected languages to some output string and simply use this to get your output like:
Dictionary<string, string> langaugeOutputMap = new Dictionary<string, string>();
languageOutputMap.Put("Java", "Java9 is coming soon");
private string concatString(string: userChosenString) {
if (languageOutputMap.containsKey(userChosenString) {
return languageOutputMap.getValue(userChosenString);
}
return string.Empty()
}
If you then want to manage multiple conditions, you could have multiple Dictionaries for each condition type and enumerate them in a collection, iterate over them when given a variable sized set of conditions and make sure that all the conditions evaluate through the use of containsKey().
Also, you can use params to specify variable length function arguments like so:
public string manyArgs(params string[] stringArgs) {
}
Also, look at PredicateBuilder:
http://www.albahari.com/nutshell/predicatebuilder.aspx
My intentions are to show a letter and have the user type the letter, while after they have hit the corresponding key (whether it's right or wrong) it is to then display the next key. I can only make this happen, at the moment, after pressing the key and then pressing the enter key following so that it finishes the scanner.next() method. Any way that I could automate the enter key so that I could make it scan in the character letter and then automatically continue to the next randomly generated character? Let me know if there needs to be clarification on this.
//some initialized code here
for(int i = 0; i < 5; i++)
{
int letterToDisplay = rand.nextInt(26)
System.out.printf("%s\r\n", letters[letterToDispaly]);
**String inputLetter = scanner.next();**
if(intputLetter.exquals(letters[letterToDisplay]))
{
letterCounter(letterToDisplay);
}
}
//some methods etc. here
Thanks,
Kyle P.
There is no portable way to read user input from a console character-by-character using the standard API; for example the Unix terminal is by default line-buffered which means that the OS does not transfer characters into the application's buffer until the user hits enter. You can't do it even from standard C.
You need to run code specific to the OS and terminal to achieve this, ideally wrapped in a library, like the ones discussed here: What's a good Java, curses-like, library for terminal applications?
A better option is using a graphical user interface. It's not the 1970s anymore ;)
Hy,
Lets say you have Varchar-Database values in a column that are cAmeLCaSe and you always want to display them UPPERCASE in a view.
Is it now better to select those entrys using the (for example) UPPER-Function of Oracle
or to loop the results and call the .toUpperCase() Method from within the Java Code after the selection has been made?
I know its a bit of a general question and i will of corse comment after having made performance messurments of the above two possibilitys. But i am more after a good source of information that addresses such questions in general (like for example "is it better do run sorting db- side or in programm-code?" and questions like this for common Solutions like .Net/Java and Oracle/ MSSQL Server.
Many thanks you took the time to read this questions, i appreciate any input and wish you a great day.
Regards
Jan
It depends on where and how the uppercased value is used.
If this is only used in the frontend (I assume with "view" you did not mean a database view) then I'd go for a toUpperCase() ideally using the user's locale.
If you are using the uppercase value for comparison I'd use the Oracle function to ensure that the you have a consistent behaviour. I'm think of e.g. a condition where you compare the column value to a string constant: WHERE upper(foobar) = upper('SomeValue') If you used Java's toUpperCase() that might apply different (locale dependent) rules than Oracle would use.
I believe always my code should be database independent.
String upper = string.toUpperCase();
Because,it's database independent.If I shift my database to some other,I need not to change my code.
In a nutshell your specific requirements should take in to consideration.
Alright, i have an assignment and i dont know how to parse the file. Is string tokenizer my best option?
The file has commas, newlines and spaces. S is the starting state and small a is the input and the big A is the next state. Should i parse the file into seperate variables and run it through a switch case to simulate a state machine?
This is the file
‘Ends in a
2
S, a, A
S, b, S
A, a, A
A, b, S
F: A
aba
bbaabba
bbabab
aaaab
b
a
Thank you so much because i just cant seem to get started...
My biggest question is how can i parse the file?
Like any other text file. There are literally millions of examples on how to do this on the web.
I would look for examples using the Scanner class.
I am not very good at parsing files. Especially in this situation.
With practice it will get easier. Doing this assignment will help.
Should i use dilimeters?
The file has delimiters so I don't why you wouldn't.
comma and newline?
Your file has commas, newlines and spaces.
and put the states into an array and the inputs ( a,b) into a second array?
Java is an object orientated programming language. Perhaps using Collections like Map and Objects is a better choice.
Should i check for digits, isaplha?
I would just assume the file is formatter correctly and read numbers when you expect to have a number and strings when you expect to have a word/token.
lower case and uppercase alpha?
Not sure if this is a consideration.
i am thinking i need a switch and a couple of cases to handle the state transitions?
If your states were handled in Java code, I would say yes. However you states are being read from a text files and stored in a data structure. In this case its simpler not to use switches.
Can someone explain how i should go about handling this file so i can process it?
Read it, store the data in a structure, process the inputs.
I am also confused on how to handle the :F A in that file..
This is information you need to record to determine when your DFA stops.
Java is an object-oriented language so build a series of classes that reflect the real world.
Example:
What do you have? And what do they need to be able to do
DFA
has a series of states
needs to be able to accept/reject input strings
State
has a collection of inputs to look for and states to transition to based on input
needs to be able to check for a token and transition to a new state
So these kind govern how you should lay out your classes (members and methods). So you should make a DFA class and it should have a method: public boolean process(String input).
I am tasked with creating a small program that can read in the definition of a FSM from input, read some strings from input and determine if those strings are accepted by the FSM based on the definition. I need to write this in either C, C++ or Java. I've scoured the net for ideas on how to get started, but the best I could find was a Wikipedia article on Automata-based programming. The C example provided seems to be using an enumerated list to define the states, that's fine if the states are hard coded in advance. Again, I need to be able to actually read the number of states and the definition of what each state is supposed to do. Any suggestions are appreciated.
UPDATE:
I can make the alphabet small (e.g. { a b }) and adopt other conventions such as the
start state is always state 0. I'm allowed to impose reasonable restrictions on the number of
states, e.g. no more than 10.
Question summary:
How do I implement an FSA?
First, get a list of all the states (N of them), and a list of all the symbols (M of them). Then there are 2 ways to go, interpretation or code-generation:
Interpretation. Make an NxM matrix, where each element of the matrix is filled in with the corresponding destination state number, or -1 if there is none. Then just have an initial state variable and start processing input. If you get to state -1, you fail. If you run out of input symbols without getting to the success state, you fail. Otherwise you succeed.
Code generation. Print out a program in C or your favorite compiler language. It should have an integer state variable initialized to the start state. It should have a for loop over the input characters, containing a switch on the state variable. You should have one case per state, and at each case, have a switch statement on the current character that changes the state variable.
If you want something even faster than 2, and that is sure to get you flunked (!), get rid of the state variable and instead use goto :-) If you flunk, you can comfort yourself in the knowledge that that's what compilers do.
P.S. You could get your F changed to an A if you recognize loops etc. in the state diagram and print out corresponding while and if statements, rather than using goto.
One non-hardcoded way to represent an automaton is as a transition matrix, which allows to represent for each current state, and each input character, what the next state is.
You haven't actually asked a question. You'll get more and better help if you have a specific question for a specific task (but still give the overall goal). The question should be narrow in scope (e.g. not "How can I implement an FSA?").
As for how to represent an FSA (which seems to be what you're having difficulties with), read on.
Start by considering the definition of an FSM: it's an alphabet ∑, a set of states S, a start state s0, a set of accept states A and a transition function δ from a state and a symbol to a state. You have to be able to determine these properties from the input. Any states not reachable by the transition function can be dropped to produce an equivalent FSM. The minimal set of states and alphabet are thus implicit in the transition function; you could make your FSM easier to use (and harder to implement, but not much harder) by not requiring either ∑ or S in the input.
You don't need to use the same representation for states that the input uses. You could use unsigned integers for your internal representation, as long as you have a map from integers to strings and strings to integers so you can convert between the internal representation and external representation. This way, your transition function can be stored as an array, so the transition step can be performed in constant time.
A simpler approach would be to use the external representation as your internal representation. With this option, the transition function would be stored as a map from strings and symbols to strings. The transition step would probably be O(log(|S|+|∑|)), given the performance of most map data structures. If symbols are represented as integers (e.g. chars), the transition function could be represented as a map from strings to an array of strings, giving O(log(|S|)) performance.
Yet another optionmodeled after the graph view of an FSM, is to create a class for states. A state has a name (the external representation). States are responsible for transitions; send a symbol to a state and get back another state.
class State {
property name;
State& transition(Symbol s);
void setTransition(Symbol s, State& to);
}
Store the set of states as a map from names to states.
There you go, three different places to start, each with a different way to represent states.
Stop thinking about everything at once. Do one thing at a time
- come with language of state machine
- come with language for stimulus
- create sample file of one state machine in language
- create sample file of stimulus
- come with class for state
- come with class for transition
- come with class for state machine as set of states and transitions
- add method to handle violation to state class
- code a little parser for language
- code another parser for language
- initial state
- some output thing like WriteLn here and there
- main method
- compile
- run
- debug
- done
The way the OpenFst toolkit does it is: A FSM has a vector of states, each of which has a vector of arcs. Each arc has an input (and output) label, a target state ID and a weight. You could take a look at the code. Maybe it will inspire you.
If you're using an object-oriented language like Java or C++, I'd recommend that you start with objects. Before you worry about file formats and the like, get a good object model for a finite state automata and how it behaves. How will you represent states, transitions, events, etc.? Will your FSA be a Composite? Once you have that sort of thing working you can get the file formats right. Anything will do: XML, text, etc.