dimanche 19 avril 2015

Javascript: Find douplicated values from array with keys

Title is pretty much self explanatory...


I want to be able to find duplicated values from JavaScript array.


The array keys can be duplicated so I need to validate only the array values.


Here is an example :



var arr=[
Ibanez: 'JoeSatriani',
Ibanez: 'SteveVai',
Fender: 'YngwieMalmsteen',
Fender: 'EricJohnson',
Gibson: 'EricJohnson',
Takamine: 'SteveVai'
];


In that example:


the key is the guitar brand the value is the guitar player name.


So:


If there is duplicated keys (like: Ibanez or Fender) as on that current example that is OK :-)


But


If there is duplicated values (like: EricJohnson or SteveVai) I'm expecting to get (return) that error:



EricJohnson,SteveVai

Data-structure to make finding all possible word completions in full English dictionary snappy on android device

Problem description


I should somehow load a full English dictionary (at least 650 000 words, possibly over a million) into a data structure that makes it fast and easy to find back all possible ways to end a String of letters in a particular order. You should also be abled to find if the String is an actual word.


The way this (game) is setup is that you continually narrow down the possible words by appending new letters to the String. This probably could make it sequentially faster to search as the game goes on and more letters are added. However, if some sort of hash-map way of implementing this is used meeting the constraints that would of course be ideal. I would rather not have the user feel that the game is (a tiny bit) slow(er) in the beginning as there are still a lot of possibilities to complete the string.


I should also be able to find if a word exists in the data structure, possibly by the same data-structure since reading in a word list twice is probably more time-consuming.


Simple example


These are just examples to make it clear what I am trying to do and that it becomes clear that it could be implemented as a narrowing search:



string: app




String[] possibleWords = dataStructure.getCompleteAbleWordsWith("app");
//possibleWords = ["app", "apps", ..., "apple", "apples", ...];



string: appl




String[] possibleWords = dataStructure.getCompleteAbleWordsWith("appl");
//possibleWords = [..., "apple", "apples", ...];


Requirements



  • Should work on cheap android devices as quickly as possible, size of the application matters less but should still be fair to the user.

  • Should be able to handle large dictionaries of over 650 000 words

  • Should be able to return list of possible words

  • Should be able to tell if a string is actually a word (could of course check if string[] is length 0)


since the dictionary is static, does not change at runtime, I would rather have it saved in a compact and easily search-able form or even better have the whole data structure object already be in machine code or something.


What I tried:



  1. I implemented a hash-map that read in all words from the dictionary and search was extremely fast and balanced for complete words. However, this approach felt wrong if I want to do this for all words and their partial forms with a key value pair that indicated true it was a word and false if not for example.

  2. Looked into multi-way trees but I felt that there could be betters ways since the tree would be very, very wide and unbalanced.

  3. Thought about SQLite, using the LIKE keyword. I have next to none experience with databases right now, so I have no clue of the performance of those, in specific on android devices.


int Cannot resolve into a variable java

problem : when i'm trying to convert int into double it's showing an error that int cannot resolve into variable . This program will input quadratic equation as input and extracts the coefficient of aX2-bX-c=0 in this format and solve the quadratic equation. But it is some error in conversion from int to double.


Program :



public static String quad (final String equation)
{
final String regex = "([+-]?\\d+)X2([+-]\\d+)X([+-]\\d+)=0";
Pattern pattern = Pattern.compile(regex);


Matcher matcher = pattern.matcher(equation);

if (matcher.matches()) {
int a1 = Integer.parseInt(matcher.group(1));
int b1 = Integer.parseInt(matcher.group(2));
int c1 = Integer.parseInt(matcher.group(3));

// System.out.println("a=" + a + "; b=" + b + "; c=" + c);
}
double a = (double) a1; // error message a1 cannot resolve into variable
double b = (double) b1; // error message b1 cannot resolve into variable
double c = (double) c1; // error message c1 cannot resolve into variable


double r1 = 0;
double r2 = 0;
double discriminant = b * b - 4 * a * c;
if (discriminant > 0){

// r = -b / 2 * a;

r1 = (-b + Math.sqrt(discriminant)) / (2 * a);
r2 = (-b - Math.sqrt(discriminant)) / (2 * a);

// System.out.println("Real roots " + r1 + " and " + r2);
}
if (discriminant == 0){
// System.out.println("One root " +r1);

r1 = -b / (2 * a);
r2 = -b / (2 * a);

}
if (discriminant < 0){
// System.out.println(" no real root");

}

String t1 = String.valueOf(r1);
String t2 = String.valueOf(r2);
String t3 ;
t3 = t1+" "+t2;
return t3;

}

c# function returning letters from a string that aren't in another

Let's say I have two strings: main_word: 'abcdefa' and check_word: 'abcd'.


I know that the letters from check_word are all in the main_word.


I have to write a function that would return me the rest of the main_word after 'using all the letters to form the check_word. In the above example the function would return the string efa.


Here's my code:



private static string getResidue(string, main_word, string check_word)
{
string result = "";
bool isFound;

foreach (char c in main_word)
{
isFound = false;
for(int i = 0; i < check_word.Length; ++i)
{
if (c == check_word[i])
{
//check_word[i] = 'x'; mark as used (this doesn't work)
isFound = true;
break;
}
}
if (!isFound) result += c;
}

return result;
}


The problem is that this version doesn't support duplicates of letters. I commented the version that would solve my problem, but unfortunately, the c# doesn't allow that line because the property of indexer cannot be assigned to - it is read only. Any ideas how to make this function work as intended?


Add 'and' before the last item in a string list

Okay so I'm trying to make a function that will take a list of items and return (not print!) a string of that list, separated by commas with an 'and' before the last item in the list. My script so far looks like this:



rose1 = Thing("red rose", "flowerbox")
rose2 = Thing("pink rose","garden")
rose3 = Thing("white rose", "vase")

def text_list(things):
"""Takes a sequence of Things and returns a formatted string that describes all of the things.

Things -> string"""
names=[o.name for o in things]
if len(names) == 0:
return 'nothing'
elif len(names) == 2:
names = ' and the '.join(names)
return 'the ' + names
else: #Here's where I need help!
names = ', the '.join(names)
return 'the ' + names


So at this point the function returns "the red rose, the pink rose, the white rose" which is great, but I need that last "and" to be put in between the pink rose and the white rose, and I can't use print. Any help? This is probably simple and I'm just missing it entirely OTL


Putting large strings of data into ExpandableListView with string-array


Problem: I want to create an ExpandableListView that when you click on a parent, it displays a child that is a stored list made in a string-array in your strings.xml file. The strings are a few sentences each.



Lots of ExpandableListView tutorials and samples online have smaller bits of data being stored. Also they are all storing them in java. That kind of sucks because what if you want to translate your app and you are handling a list of longer strings? It would be easier to have it in your strings.xml file. How would I display that data using code like that? I don't want to edit the data at all, it's going to remain static like reference material.


Like this one, I can see how it is doing it in java. http://ift.tt/1e1h4JP


It's using an arraylist in java to store and display data:



listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

// setting list adapter
expListView.setAdapter(listAdapter);
}

/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();

// Adding child data
listDataHeader.add("Top 250");
listDataHeader.add("Now Showing");
listDataHeader.add("Coming Soon..");

// Adding child data
List<String> top250 = new ArrayList<String>();

// Adding child data
List<String> top250 = new ArrayList<String>();
top250.add("The Shawshank Redemption");
top250.add("The Godfather");
top250.add("The Godfather: Part II");
top250.add("Pulp Fiction");
top250.add("The Good, the Bad and the Ugly");
top250.add("The Dark Knight");
top250.add("12 Angry Men");

List<String> nowShowing = new ArrayList<String>();
nowShowing.add("The Conjuring");
nowShowing.add("Despicable Me 2");
nowShowing.add("Turbo");
nowShowing.add("Grown Ups 2");
nowShowing.add("Red 2");
nowShowing.add("The Wolverine");

List<String> comingSoon = new ArrayList<String>();
comingSoon.add("2 Guns");
comingSoon.add("The Smurfs 2");
comingSoon.add("The Spectacular Now");
comingSoon.add("The Canyons");
comingSoon.add("Europa Report");

Java program to extract coefficents from quadratic equation

Problem: Java program to split the coefficients from a quadratic equation eg if input string is:



String str1;
str1 = "4x2-4x-42=0"


So I need to split the coefficients from the given input string and to get output as



a = 4 b = -4 c = -42


I tried this:



String equation = "ax2+bx-c=0";
String[] parts = equation.split("\\+|-|=");
for (int i = 0; i < parts.length - 2; i++) {
String part = parts[i].toLowerCase();
System.out.println(part.substring(0, part.indexOf("x")));
}
System.out.println(parts[2]);


But I got the output as 23x2 and 4x and 4. Actual output needed is 23 ,- 4 , 4.