I want to design a language learning Android application where random set of questions are retrieved from the database and displayed to the user.
I have different type of questions such as multiple choice questions, fill in the blanks, matching the correct choice, arranging the words into a proper sentence and listening to audio and answering the comprehension questions.
How to store these different types of questions in the database and retrieved randomly and displayed to the user to be answered?
I am using SQLite.
This is a pretty broad question and there are a lot of things you need to consider. For example, the modelling of your questions, and persistence -- storing them in the DB. I made a similar Android app a few years ago.
The first thing I suggest is working in incremental steps; things are much easier if you start out with, say, multiple-choice questions only (that all have four answers). Then once you have that working, add other types of questions.
For modelling your object domain, I suggest starting with a single base Question class. This can contain some common properties, like the unique ID, the name/shortname, perhaps some sort of difficulty metric.
After this, you can have sub-types of questions, such as a MultipleChoiceQuestion, a ShortAnswerQuestion, and an EssayQuestion. They may have other properties (like the list of possible answers for mutliple choice).
Mapping all this to a bunch of tables is not trivial. The usual method is one table per class; another option is one table with all the properties for all classes, and some sort of 'type' discriminator. I suggest the former, since it's a cleaner separation of attributes.
Finally, in terms of random, there are two approaches: random on the database level (more efficient, since it returns less data) or random on the application level. The difference is "hey database, get me N random questions" vs. "hey database, get me all the questions; hey application, pick N random questions."
To leverage the DB, you can use this answer here, where they use ORDER BY RANDOM() LIMIT N. I don't know about SQLite, but in SQL Server, with large data sets, this can be extremely slow; if you have a lot of questions, profile it and see if this is too slow for your app.
If you have a base Questionstable with all questions, this will work quite easily for you. If not, you may need to do something similar where you poll forAmultiple choice questions,Bshort answer questions, etc. whereA + B + ... = N` number of questions you want.
The approach I use for this type of problem is to uniquely identify each of your rows. A sequence ID is fine.
Each time you go through the loop, place all of the IDs into an array structure. Each entry in the array has a random number and an ID into your SQLite table.
After you do this, sort the array and now you have randomly sequenced the questions. Process in order.
Your question is too abstract, still trying to answer your question.
First of all, you will need to create a database which will contain a table that uniquely identifies your questions.
And then, you can fire the query as:
SELECT * FROM table ORDER BY RANDOM() LIMIT 1; which can be used for selecting a random row from sqlite table.
And then, simply code for displaying that question.
Related
Im trying to better organise the types of tasks regularly sent to my team based off of the titles and short comment people enter.
Our team only handles a handful of issues (maybe 10 or so) different types of tasks, so I've put together a list of common words used within the description of a particular type of task and i've been using this to categorise the issues. for example.... an issue might come through like "User x doesn't have access to office after hours, please update their swipecard access level". what i've got so far is if the comments contain 'swipecard' or 'access', its a building access type request.
I've quickly found myself with code that's LOTS of ... if contains, and if !contains...
Is there a neater way of doing what im after?
If you want to make it complex, it sounds like you have a classification problem.
If you want to keep it simple, you're probably on the right track with your if statements and contains(). To get to a cleaner solution, I would approach it as follows:
Create a class to modify your categories - give it two attributes: String categoryName, List<String> commonlyUsedWords;
Populate a list with instances of that class - one per type.
For each issue, loop through the list of categories and check how many words match, and store that as a percentage (e.g. 8 out of 10 words match, therefore 80% match).
Return the category with the highest match rate.
I want to code a simple project in java in order to keep track of my watched/owned tv shows, movies, books, etc.
Searching and retrieving the metadata from an API (themovieDB, Google Books) is already working.
How would I store some of this metadata together with user-input (like progress or rating)?
I'm planning on displaying the data in a table like form (example). Users should also be able to search the local data with multiple attributes. Is there any easy way to do this? I already thought about a database since it seemed that was the easiest solution.
Any suggestions?
Thanks in advance!
You can use lightweight database as H2, HSQLDB or SqlLite. These databases can be embedded in the Java app itself and does not require extra server.
If your data is less, you can also save it in XML or Json by using any XMLParser or JsonParser (e.g. Gson()).
Your DB table will have various attributes which are fetched from API as well as user inputs. You can write query on the top of these DBs to fetch and show the various results.
Either write everything to files, or store everything on a database. It depends on what you want though.
If you choose to write everything to files, you'll have to implement both the writing and the reading to suit your needs. You'll also have to deal with read/write bugs and performance issues yourself.
If you choose a database, you'll just have to implement the high level read and write methods, i.e., the methods that format the data and store it on the appropriate tables. The actual reading and writing is already implemented and optimized for performance.
Overall, databases are usually the smart choice. Although, be careful of which one you choose. Some types might be better for reading, while others are better for writting. You should carefully evaluate what's best, given your problem's domain.
There are many ways to accomplish this but as another user posted, a database is the clear choice.
However, if you're looking to make a program to learn with or something simple for personal use, you could also use a multi dimensional array of strings to hold the name of the program, as well as any other metadata fields and treat the array like a table in excel. This is not the best way to do it, but you can get away with it with very simple code. To search you would only need to loop through the array elements and check that the name of the program (i.e. movieArray[x][0] matches the search string. Once located you can perform actions or edit the other array indexes pertaining to that movie.
For a little more versatility, you would create a class to hold the movie information with fields to hold any metadata. The advantage here is that the metadata fields can be different types rather than having to conform to the array type, and their packaged together in the instance of the class. If you're getting the info from an API then you can update or create the classes from the API response. These objects can be stored in an ArrayList and searched with a loop that checks for a certain value i.e.
for (Movie M : movieArrayList){
if(m.getTitle().equals("Arrival")){
return m;
}
}
Alternatively of course for large scale, a database would be the best answer but it all depends what this is really for and what it's needs will be in the real world.
My assignment is to create a simple Quiz app for Android. I am NOT looking for the code for this.. I am simply looking for someone to possibly lay out how to get started with this (pseudo-code ish).
The program is suppose to display one term and four definitions; one of them being the correct one. Once the user selects which one they think it is, the program will tell the user if it was correct / incorrect using a toast message.
Specs:
The terms need to be randomly selected, and only displayed once per run. However the definition needs to stay in the pool of definitions for other questions.
Definitions randomally selected (except the right one)
Program ends if it runs out of terms to display
Needs to use an ArrayList to hold collections of items, and a HashMap to hold name-value pairs.
Must use Androids logging mechanism to log error messages (via try/catch statements).
If you can help me out by guiding me in the right direction, that would be great :) Thanks!
I would (as always in object-oriented languages) start by mapping your problem to real-live objects. In your case, there would be two:
A Question-class which holds four answers, the question and offers a method to check if the given answer was correct.
An Answer-class which holds a single answer and whether it's correct or not.
As for your storage question, I wouldn't use a HashMap at all. Store the Question-instances in an ArrayList and use a Random.nextInt()-method to get a random question from your list.
In your Question-class, you would store all possible answers in another ArrayList. To randomize the order in which the answers are presented, you can use the Collections.shuffle()-method.
For the presenting part, have your Question-class return the question (string) and the four answers (strings) and put the into your widgets. To identify the answer given, you can use the Answer-instance (using the array-index is easier, but it is more error prone).
To check if the right answer was given, query your Question-classes isCorrect(Answer)-method and check if the given instance in the internal ArrayList is marked as the correct one.
I'm building a RPG dungeon game in Java and I'm stuck on creating a data structure.
I have a lot of Thing objects that I can copy to populate a dungeon with. For instance, there is a bread Thing object, and a sword Thing object, a chain mail Thing object, and monster Thing(s), etc. I want to store them in a central Library and then be able to retrieve an object using certain queries. I want to store them using the following fields:
int minLevel
int maxLevel
double probability
int[] types
So a rusty sword would have a minLevel of 1, a maxLevel of 3, a probability of rarity(3%),and [type.SWORD,type.WEAPON,type.ITEM,TYPE.EQUIP]. A better sword would have minLevel 2, maxLevel 10, rarity (1%).
Then I want to retrieve a random type.SWORD from the library and say I'm at level 3. I should get a rusty sword more often than the better sword based on their probabilities. If I retrieved a type.SWORD from the library requesting level 10, I would only get back the better sword.
I hope this makes sense.
EDIT
At the initialization stage, all the basic objects will be created. Things like the available weapons, armor, foods, potions, wands, all the basic possible Things that have a unique graphic tile in the game. Then when I want to place an object somewhere, I just make a copy of one of the available Things, adjust it's stats a little, and plunk it down in the world. The actual items are all subclass of the root Thing class, such as class Creature,Item,Equip(extends Item),Weapon(extends Equip),Armor(extends Equip),Food(extends Item), etc. But I want to tag them different in the Library database, I want to use extra tags, such as type.RARE, type.ARTIFACT, type.CURSED, so I want extra tags besides the class.
The game use LIBGDX to be available on Android and as an Applet. I use the free Rltile set, which has thousands of good tiles. I will use Pubnub or Google App Engine to provide multiplayer support.
i can think of three answers:
write your own Library that stores these things in Maps with custom methods.
so you might have a Map<Type,List<Object>> that stores lists of things by type
and then a method that takes a type, retrieves the list from the map, and selects
something by probability (that's easy to do - you just some up the probabilities,
generate a random number between 0 and the sum, and then walk through the list,
subtracting the item's probability from your random value until it's negative - you
return the item that made it negative[*]). you can also filter the list first by
level, for example.
if you have a real mix of different things, and don't want to base this on types,
then another option (slower, but more flexible) is to place everything in a list
and then filter by your needs. a nice way to do that is with guava - see
Iterables.filter and Predicate at https://code.google.com/p/guava-libraries/.
you could provide an interface that takes a predicate and returns a random
selection from whatever is left after filtering. predicates are easy to construct
"inline" with anonymous classes - see examples at
https://code.google.com/p/guava-libraries/wiki/FunctionalExplained#Functions_and_Predicates
stick all this in a database. maybe i am too enterprisey, and games people would
never do this, but it seems to me that a small, embedded database like sqlite or
H2 would be perfect for this. you can then select things with SQL queries (this
is already a long answer so i won't give more details here).
change your design. what you describe is not very OO. instead of having types,
your Things could implement interfaces. so the Weapon interface would have a
getMinLevel() method, for example. and then, with a design like this, use a
database with ORM (hibernate).
what you're doing is kind of ambitious and i suspect is more about learning than anything else (no criticism intended - this is how i learn stuff, by making things, so just assuming you are like me). so choose whichever you feel most comfortable with.
[*] this assumes that you always want to return something. if the probabilities are normalized and you want to be able to return nothing, select the initial value from 0-1 (or 0-100 if using percentages). and, if nothing turns the value negative when you run through the list, return nothing.
The easiest approach is to put all your objects in a single large arraylist, and use repeated sampling to select an object.
The procedure to select a random item is very simple:
Select a random number from 0 up to the size of the ArrayList
Get the object at that index from the library
If the object fails to meet any criteria you specify (e.g. "is a of type.SWORD or type.MACE?") go back to start
If the object is outside the minimum or maximum level, go back to start
If the object has a rarity of less than 100%, create a random number from 0-100%. If the random number exceeds the object's rarity, loop back to start. Most objects should have a rarity of say 10-100%, if you want extremely common objects then you can add them multiple times to the library.
This procedure will produce an object that meets the criteria sooner or later (if it exists) and will do so according to the rarity percentage.
The one slight trickness is that it will loop infinitely if no such object exists. Suppose there is no weapon in the library at level 17 for example? To get around this, I would propose widening the minLevel and maxLevel after every 100 tries to ensure that eventually one is found. Ensure you always have a level 1 object of each type available.
For safety, you might also want a bailout after say 100,000 tries (but remember to throw an exception - this is a problem if you are asking for things that don't exist in the library!).
P.S. I implemented a similar library system in a roguelike game called Tyrant that I created many years ago. Source is here if you are interersted:
https://github.com/mikera/tyrant/blob/master/src/main/java/mikera/engine/Lib.java
I am developing a financial manager in my freetime with Java and Swing GUI. When the user adds a new entry, he is prompted to fill in: Moneyamount, Date, Comment and Section (e.g. Car, Salary, Computer, Food,...)
The sections are created "on the fly". When the user enters a new section, it will be added to the section-jcombobox for further selection. The other point is, that the comments could be in different languages. So the list of hard coded words and synonyms would be enormous.
So, my question is, is it possible to analyse the comment (e.g. "Fuel", "Car service", "Lunch at **") and preselect a fitting Section.
My first thought was, do it with a neural network and learn from the input, if the user selects another section.
But my problem is, I donĀ“t know how to start at all. I tried "encog" with Eclipse and did some tutorials (XOR,...). But all of them are only using doubles as in/output.
Anyone could give me a hint how to start or any other possible solution for this?
Here is a runable JAR (current development state, requires Java7) and the Sourceforge Page
Forget about neural networks. This is a highly technical and specialized field of artificial intelligence, which is probably not suitable for your problem, and requires a solid expertise. Besides, there is a lot of simpler and better solutions for your problem.
First obvious solution, build a list of words and synonyms for all your sections and parse for these synonyms. You can then collect comments online for synonyms analysis, or use parse comments/sections provided by your users to statistically detect relations between words, etc...
There is an infinite number of possible solutions, ranging from the simplest to the most overkill. Now you need to define if this feature of your system is critical (prefilling? probably not, then)... and what any development effort will bring you. One hour of work could bring you a 80% satisfying feature, while aiming for 90% would cost one week of work. Is it really worth it?
Go for the simplest solution and tackle the real challenge of any dev project: delivering. Once your app is delivered, then you can always go back and improve as needed.
String myString = new String(paramInput);
if(myString.contains("FUEL")){
//do the fuel functionality
}
In a simple app, if you will be having only some specific sections in your application then you can get string from comments and check it if it contains some keywords and then according to it change the value of Section.
If you have a lot of categories, I would use something like Apache Lucene where you could index all the categories with their name's and potential keywords/phrases that might appear in a users description. Then you could simply run the description through Lucene and use the top matched category as a "best guess".
P.S. Neural Network inputs and outputs will always be doubles or floats with a value between 0 and 1. As for how to implement String matching I wouldn't even know where to start.
It seems to me that following will do:
hard word statistics
maybe a stemming class (English/Spanish) which reduce a word like "lunches" to "lunch".
a list of most frequent non-words (the, at, a, for, ...)
The best fit is a linear problem, so theoretical fit for a neural net, but why not take immediately the numerical best fit.
A machine learning algorithm such as an Artificial Neural Network doesn't seem like the best solution here. ANNs can be used for multi-class classification (i.e. 'to which of the provided pre-trained classes does the input represent?' not just 'does the input represent an X?') which fits your use case. The problem is that they are supervised learning methods and as such you need to provide a list of pairs of keywords and classes (Sections) that spans every possible input that your users will provide. This is impossible and in practice ANNs are re-trained when more data is available to produce better results and create a more accurate decision boundary / representation of the function that maps the inputs to outputs. This also assumes that you know all possible classes before you start and each of those classes has training input values that you provide.
The issue is that the input to your ANN (a list of characters or a numerical hash of the string) provides no context by which to classify. There's no higher level information provided that describes the word's meaning. This means that a different word that hashes to a numerically close value can be misclassified if there was insufficient training data.
(As maclema said, the output from an ANN will always be floats with each value representing proximity to a class - or a class with a level of uncertainty.)
A better solution would be to employ some kind of word-relation or synonym graph. A Bag of words model might be useful here.
Edit: In light of your comment that you don't know the Sections before hand,
an easy solution to program would be to provide a list of keywords in a file that gets updated as people use the program. Simply storing a mapping of provided comments -> Sections, which you will already have in your database, would allow you to filter out non-keywords (and, or, the, ...). One option is to then find a list of each Section that the typed keywords belong to and suggest multiple Sections and let the user pick one. The feedback that you get from user selections would enable improvements of suggestions in the future. Another would be to calculate a Bayesian probability - the probability that this word belongs to Section X given the previous stored mappings - for all keywords and Sections and either take the modal Section or normalise over each unique keyword and take the mean. Calculations of probabilities will need to be updated as you gather more information ofcourse, perhaps this could be done with every new addition in a background thread.