How to split a string to get related data JAVA - java

I have string from which I am getting data in array but I am not getting way to get so that I get related data in array like my string is,
[{"Class Room": ["Windows", "Windows1"], "Staffroom": ["Windows", "Windows1"]}], "
here i have two dropdowns ,
"Class Room" having two values in dropdown Windows and Windows1
another drodown,
"Staffroom" having two values in dropdown Windows and Windows1
How would i get dropdown related value in array i can use split operation but cant getting logic
Above given string is in list, my code is ,
String[] data = list.toString().split(",");
But it split in array then I would not have related data
I want it to split in way so that I would get relative dropdown data in array,
"Class Room": ["Windows", "Windows1"], value in aray index 0
"Staffroom": ["Windows", "Windows1"]}] value in array index 1
String is not fix it is generating on run time number of dropdown and values of dropdown vary time to time but pattern of string same as mentioned above

This depends on the UI framework that you are working. If you are using Swings then you have to use ActionListener to display related data. For example
private String s1[] = { "None", "J2EE", "DataBase", "Scripting Language",
"Computer Networks" };
private String s2[][] = { { "None" }, { "Core Java", "Advanced Java" },
{ "Oracle", "SQL", "SyBase" }, { "Java scripts", "c#", "CGI" },
{ "MCSE", "CCNA", "CCNP", "CCIE" } };
...
skill = new JComboBox(s1);
specificSkill = new JComboBox(s2[0]);
...
skill.addActionListener(new ComboAction());
...
specificSkill.setSelectedIndex(0);

You can use this code which can solve your problem as it is tested and verified.
String temp = "[{"Class Room": ["Windows", "Windows1"], "Staffroom": ["Windows", "Windows1"]}],";
String parts[] = temp.split(",");
ArrayList<String> listItems = new ArrayList<String>();
for (int i = 0; i < parts.length; i =i+2) {
listItems.add(parts[i]+","+parts[i+1]);
}
Or you can use regex to break the string at a particular occurence of a character.
I hope it helps.

Related

With 2 sets of strings, find a string that can be constructed from either set

Given the following sets of strings:
are yo
you u
how nhoware
alan arala
dear de
I need to find a sequence that can be constructed by concatenating the strings in either columnm, and it must use the same number of elements in both cases.
For example, "dearalanhowareyou" can be constructed from both sets of strings, using 5 elements each time.
A invalid choice would be "dearalanhoware" since it would use 4 elements from the left column but only 3 from the right
The problem is taken from here:
https://open.kattis.com/problems/correspondence
I'm using this site to improve for future job interviews and I just can't seem to figure this one out at all.
My only working implementation is a brute force approach taking every possible combination of each set which is not a very good solution due to time complexity.
My code right now:
list1 = getPermutations("",send1);
list2 = getPermutations("",send2);
ArrayList<String> duplicateValues = new ArrayList<String>();
for (int i = 0; i < list1.size(); i++) {
if (list2.contains(list1.get(i))) {
duplicateValues.add(list1.get(i));
}
private static ArrayList<String> getPermutations(String currentResult, ArrayList<String> possibleChars) {
ArrayList<String> result = new ArrayList<>(possibleChars.size());
for (String append : possibleChars) {
String permutation = currentResult + append;
result.add(permutation);
if (possibleChars.size() > 0) {
ArrayList<String> possibleCharsUpdated = (ArrayList) possibleChars.clone();
possibleCharsUpdated.remove(new String(append));
result.addAll(getPermutations(permutation, possibleCharsUpdated));
}
}
return result;
}
You can significantly narrow down the amount of permutations that you need to check by finding which words from each set could possibly begin the constructed String. In this case, the only two choices are dear and de because de is a substring of dear. Once you get the String started you can take a substring of the longer String, in this case "dear".substring("de".length()) returns ar which tells you that the next element from the right side needs to start with ar. So basically you have two cases :
String stringLeft = "", stringRight = "";
if(stringLeft.length() == stringRight.length())
{
//find two matching Strings here (one is substring of another)
String[] matching = getMatching(); //returns 1d array of size 2(if only two strings match)
stringLeft += matching[0];
stringRight += matching[1];
}
else
{
if(stringLeft.length() > stringRight.length())
{
String start = stringLeft.substring(stringRight.length());
//find string on right that starts with start
stringRight += getStringStartingWith(start);
}
else
{
String start = stringRight.substring(stringLeft.length());
//find string on left that starts with start
stringLeft += getStringStartingWith(start);
}
}
The only thing you need to look out for is if there are multiple matching Strings, or Strings starting with the substring you're looking for.

How to get string data of one column as an array data from data base

In an app I have used 7 checkboxes to get the days name from user and I am storing those name in an array based on selected checkboxes and then converting them to String data and store in database now I want to get the data back as an array only.
for eg:
days={"Mon","Tue","Wed","Sat"}
And now the database column has this value as: [Mon,Tue,Wed,Sat] which is stored as a String.
I can get this string back but how to convert it back to array so that i can compare the array data with current day like if today is Mon so i can find out which column has Mon.
Please help me out as I don't know what to search any related link or post or any suggestions how to achieve this. Thanks.
You can do it like this. Though, your values should not have "," in them.
String[] strs = new String[] { "Foo", "Bar", "Baz" };
String joined = Arrays.toString( strs );
String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);
// String.split()
String[] resplit = joinedMinusBrackets.split( ", ");
you can refer this post
or you convert the resultset into an array using getArray() method, javadoc

Ranking text based on keywords provided

I have a set of Strings and a set of keywords.
Example
String 1 : Oracle and Samsung Electronics have reportedly forged a new partnership through which they will work together to deliver mobile cloud services. In a meeting last Thursday, Oracle co-CEO Mark Hurd and Shin Jong-kyun, head of Samsung Electronics’ mobile
String 2 : This is some random string.
Keywords : Oracle,Samsung
The function should return String 1 as the one having highest rank. I can search each strings for each keywords, but it will take too much time as there will be lot of strings and a huge set of keywords.
Create a data structure that maps each term that appears in any of the strings to all strings it appears in.
Map<String,List<Integer>> keyword2stringId;
If a string contains the same keyword multiple times, you could simply add it to the List multiple times, or -- if you prefer -- use a slightly different map which allows you to also keep a count:
Map<String,List<Pair<Integer,Integer>>> keyword2pair; // pair = id + count
Then for each keyword, you can look up the relevant strings and find the ones with the highest overlap, for instance like so:
// count the occurrences of all keywords in the different strings
int[] counts = new int[strings.length];
for (String keyword : keywords) {
for (Integer index : keyword2stringId.get(keyword)) {
if (index != null) {
counts[index]++;
}
}
}
// find the string that has the highest number of keywords
int maxCount = 0;
int maxIndex = -1;
for (int i = 0; i < counts.length; i++) {
if (counts[i] > maxCount) {
maxCount = counts[i];
maxIndex = i;
}
}
// return the highest ranked string or
// 'null' if no matching document was found
if (maxIndex == -1) {
return null;
} else {
return strings[maxIndex];
}
The advantage of this approach is that you can compute your map offline (that is, only once) and then use it again and again for different queries.
It looks like you should try some search engine or search library like Lucene or Solr
Lucene Core, our flagship sub-project, provides Java-based indexing
and search technology, as well as spellchecking, hit highlighting and
advanced analysis/tokenization capabilities.
Solr is the popular, blazing-fast, open source enterprise search
platform built on Apache Lucene™.
Both of this stuff have support to do what you need to do - to search for some keywords and rank them.
This program can't be less than O(n) complexity, that is, you have to check each word of the string with each keyword.
Now, the only think you can do is perform the check over each string all at once:
public int getRank(String string, String[] keyword) {
int rank = 0;
for (String word : string.split(" "))
for (String key : keyword)
if (word.equals(key))
rank++;
return rank;
}
In this easy example, rank is an int increased each time a keyword occurs in the string. Then fill an array of ranks for each string:
String[] strings = new String[]{"...", "...", "...", "...", ...};
String[] keyword = new String[]{"...", "...", "...", "...", ...};
int[] ranks = new int[stringsNumber];
for (int i = 0; i < stringsNumber; i++)
ranks[i] = getRank(strings[i], keyword);
I believe what you're really looking for is TF/IDF - Term Frequency/Inverse Document Frequency. The link provided should give you the information you need, or alternatively as #Mysterion has pointed out, Lucene will do this for you. You don't necessarily need to deploy a complete Lucene/Solr/ElasticSearch installation, you could just make use of the classes you need to roll your own

Dynamically add strings from array content

I have an array, which may differ in content based on some user selections.
One of the arrays look like this:
String[] get_elements = { "firstname", "lastname", "address", "status" };
In a static function, to get what I need to end up with, I would do this:
String name = c.getString(JSON_NAME);
String address = c.getString(JSON_ADDRESS);
String status = c.getString(JSON_STATUS);
Now, what I want to do, is set a string, based on what the content of the array is, like this:
for (int x = 0; x < get_elements.length; x++) {
String get_elements[x] = c.getString(get_elements[x]);
}
The array consists of: firstname, lastname, address and status.
So i want to end up with a loop-defining them as strings and assigning values to those strings, ending up with rawcode:
string firstname = c.getString("firstname");
And so on. I've tried using String get_elements[x] = c.getString(get_elements[x]) with no luck.
Is there a way to dynamically create strings based on the array content?
No, You can't. The way you tried with array is the something you can try similar to this.
String[] elements=new String[4];
for (int x = 0; x < get_elements.length; x++) {
elements[x] = c.getString(get_elements[x]);
}
You are replacing the existing element in array. Instead try this:
String result_elements = new String[get_elements.length];
for (int x = 0; x < get_elements.length; x++) {
result_elements[x] = c.getString(get_elements[x]);
}
Hope it solves your issue.
You cannot build an execute new java code at runtime. Besides, what would be the point of a single String firstname that contains c.getString("firstname") without any further information? You are better to use c.getString("firstname") where you need that sole return value.
You have to posses information about what data corresponds to what index. Take the name "Carter" as an example in addition to the fact, that the number of indices in the array may vary based on the user's choice. How are you going to examine, if "Carter" is the firstname or the lastname?

Separate Multiple Integers from a String

I've got a question about making a save function.
I'm trying to have a string be saved as a single file to set specific settings on a game. So saveFile would read "002007...", having 002 be a player's location, then 007 a player's level, for example.
I understand how to compile the various variables into a single string, but how would I return it to individual variables?
You better go with SQLite or SharedPreferences if you really want to save settings for a game on Android.
On the other hand, if you have to stick with saving a String on a file, you might want to use a delimiter(ie \r\n or # or | would do it) between numbers. So while parsing back delimiters will help you a lot, but beware when things get complicated a single String won't do the thing nicely. Then you might want to use JSON (for simplicity I would prefer gson) to encode your settings into one String and vice verse.
You could use a delimiter between the values like this:
int location = 02;
int level = 3;
int powerUps = 46;
... and so on
String saveString = location + "#" + level + "#" + powerUps + "#" + ...
Then to load the String back into variables:
String[] values = saveString.split("#");
location = values[0];
level = values[1];
powerUps = values[2];
... and so on
My advice is to check out Shared Preferences and you can read Android's documentation on it here.
If you did want to use your single String, file method, I suggest using delimiters. That simply means to put commas, or other types of delimeters in between different integer values. Instead of "002007", save it as "002,007". Example:
String s = "002,007"
String[] values = s.split(","); // values[0] is "002" and values[1] is "007"
Using the .split(String) command will return a String array with each element in the array containing parts of the String that was split up by the parameter, in this case: ,
If you wanted to separate values per person, something like this could be done:
String s = "002,007;003,008";
String[] people = s.split(";"); // people[0] is "002,007", people[1] is "003,004"
String[][] person = new String[people.length][people[0].split(",").length];
for (int i = 0; i < people.length; i++)
{
person[i] = people[i].split(",");
}
Here is what the array would then contain:
person[0][0] is "002"person[0][1] is "007" person[1][0] is "003" person[1][1] is "008"
// print it for your own testing
for (String ppl[] : person)
{
for (String val : ppl)
{
System.out.print(val + " ");
}
System.out.println("");
}

Categories