Comparing any of these value from an array Efficiently - java

I am having an Array of String of 10 elements.
Now I need to compare my value available in any of these Arrays value.
1 Option I thought of sorting the array and then binary search on the
same
But further analysis, I found the value needed to be compare is not exactly same, it contains some value , but even in that case, it should be successful.
Like Value to compare ,
String str = "Author"
String[] arrays = {"#Author","#Auth",#Au...}
str.contains(arrays..) actually but how to do the same .

you could use Dynamic Programming:
http://www.algorithmist.com/index.php/Longest_Common_Subsequence
this algorithm check the longest subsequence of string with the minimum complex
This is the algor in java:
http://introcs.cs.princeton.edu/java/96optimization/LCS.java.html

If you are only dealing with an array with only 10 elements... you don't need to worry about efficiency!
You can simply loop through the entire array, or instead of using a String[] use an List<string> and use the contains method.

Related

What data structure can I use to hold elements of an array if the array elements start with a string without looping through the initial array

I am trying to implement an autocomplete method that receives an input string and searches through a given array of words for the words that have the input string as the prefix of the words in the array.
I have successfully implemented this by looping through the array of words and returning all the elements with the prefix of given input string. However, I believe that there should be an optimal way of doing this as I realized that I am looping through all elements of the array after sorting the elements.
I want to select only elements in the array that begin with the first letter of the given string and then search that sub-array for the words that have the string as their prefix. This will cut the processing time considerably and provide an optimal solution.
What data structure can I use that will not require me to loop through the entire given array, or dictionary key (I tried implementing this using a map), but only chose the sub-array containing elements close to the solution?
PS: I also played with ArrayUtils.subArray() of Apache Commons but could not retrieve the sub-array. Any ideas on how to implement this?
You could use a TreeSet. Once populated, given a String prefix you could get all matching words by
Set<String> findWords(String prefix) {
// copied from https://stackoverflow.com/questions/4002021/increment-last-letter-of-a-string
int len = prefix.length();
String allButLast = prefix.substring(0, len - 1);
String endPrefix = allButLast + new Character(prefix.charAt(len - 1) + 1);
return treeSet.subSet(prefix, endPrefix);
}

Sort integers having special character in Java

I have a problem where I need to sort Integers separated by hyphen either in ascending or descending order.
I tried using
Collections.sort(list, Collections.reverseOrder());
Where list is an instance of ArrayList created, but its not giving me the exact result.
The arrayList looks like this:
[91,95,96-1,94-2,94-1,100-2].
The expected way is:
[91,94-1,94-2,95,96-1,100-2]
Using the default sorting on Strings will use a lexicographical order, whereas you intend to sort the Strings in a numerical order (and if the first number is equal, by the second number). A way to accomplish this is by using two Comparators:
List<String> list = new ArrayList<>(Arrays.asList("96-1","91","94-2","100-2","94-1","95"));
System.out.println("Unsorted: "+list);
Comparator<String> primaryComparator =
(a,b)->Integer.valueOf(a.split("-")[0])
.compareTo(Integer.valueOf(b.split("-")[0]));
Comparator<String> secondaryComparator =
(a,b)->Integer.valueOf(a.split("-")[1])
.compareTo(Integer.valueOf(b.split("-")[1]));
list.sort(primaryComparator.thenComparing(secondaryComparator));
System.out.println("Sorted: "+list);
list.sort(primaryComparator.thenComparing(secondaryComparator).reversed());
System.out.println("Sorted in reverse: "+list);
Try it online.
As for the comparators themselves, I assumed the Strings in the list are always valid, and always of the form \d+(-\d+)?, so either an integer, or two integers separated with a hyphen. (If this is not the case, you might want to add some additional checks/validations with a custom Java 7 style comparator to make it more readable then the Java 8 style lambdas.)
The .split("-")[0] / .split("-")[1] will split this String on the hyphen, and takes either the first or last integer depending on the comparator. It will then convert this to an integer with Integer.valueOf(...), and will use the default integer comparing builtin Integer1.compareTo(Integer2).

Use of 'new' for arrays in Java

I've been undertaking some basic tutorials. One of which has asked me to set up an array to hold the following string values:
Beyonce (f)
David Bowie (m)
Elvis Costello (m)
Madonna (f)
Elton John (m)
Charles Aznavour (m)
Write a program to loop round, count how many are male vocalists and how many are female, and display my answer in the console.
I managed to complete it, but the way I set up my array was different to the answer provided.
Mine is as follows:
String names[] = {"Beyonce (f)", "David Bowie (m)", "Elvis Costello (m)", "Madonna (f)", "Elton John (m)", "Charles Aznavour (m)"};
And the provided answer is as such:
String[] singers = new String[6];
singers[0] = "Beyonce (f)";
singers[1] = "David Bowie (m)";
singers[2] = "Elvis Costello (m)";
singers[3] = "Madonna (f)";
singers[4] = "Elton John (m)";
singers[5] = "Charles Aznavour (m)";
Should I be creating a "new" array? If so, why? And what is the difference between the two?
Your answer is equivalent but more readable and less error-prone because you don't need any "magic numbers" for each array element with the "fear" of accessing an element out of the array definition and therefore creating an IndexOutOfBoundsException.
Both are doing the same thing.
First approach is more dynamic. You are telling java compiler that those elements will create an array. Compiler knows in compilation time their length, so it creates an array to fit them all.
In your second attepmt, you are first creating an array with length of 6. And then put in every slot one object.
When to use them:
If you know from the start what elements will be in the array, use first aproach - it is cleaner, shorter
But if there is some sort of logic that determined who should be placed in each slot, then second would be better. Like, when you want to create a 10 size array, but you will fill it during the runtime.
First aproach is also safer, because compiler created the array based on input length. Adding new element in code will change array size. In the second aproach you would have to change size manually, or ArrayOutOfBoundException will be thrown when adding singers[6].
But if you don't know the length of array (you will fill list in runtime), then you must use List or other dynamic structure (Set, List)
Both are valid ways to initialize an array.
Your way of initializing the array can only be done in the same expression that defines the array variable, though it can later be done in a similar way :
String[] names = null;
names = new String[] {"Beyonce (f)", "David Bowie (m)", "Elvis Costello (m)", "Madonna (f)", "Elton John (m)", "Charles Aznavour (m)"};
The provided answer explicitly creates an array of Strings, specifies the number of Strings that this array can store, and assigns values to the indices of the array.
Both solutions are correct. The first one uses an array initializer, the second one first instantiates the array and then populates it with values. One could argue that the first solution is more robust, since in the second solution the length of the array must be explicitly given before the entries are provided and it is possible to use indices beond the capacity of the array, which will be only detected at runtime.
A new array can be created with the new operator followed by the array element type and the array size between the [ ] characters - this is called the Array Creation Expression. Or when you declare a variable, you can also use an array literal which is called Array Initializers (but this cannot be used to assign a value to an array later on just when it is declared).
When you write
String names[] = {"A", "B", "C"};
It is just a short form and is equivalent to
String[] names = new String[] {"A", "B", "C"};
Note that to indicate that an array of the specified type is to be declared, both String[] names and String names[] forms can be used and they are equivalent, altough:
String names[], names2; // Only names is an array, names2 is just a String
While
String[] names, names2; // Both names and names2 are arrays!
It is recommended to use the second form to avoid confusion and accidents if later you add more variable names to the declaration.
Let's take a closer look of what happens in the 2 cases:
// "Slow" filling
String[] names = new String[3]; // Filled with null values by default
names[0] = "A"; // Explicit index, index range check!
names[1] = "B"; // Explicit index, index range check!
names[2] = "C"; // Explicit index, index range check!
// "Fast" filling at creation time, implicit indices and array length,
// No index checks!
String[] names = {"A", "B", "C"};
Advantages of creating and initializing the array in one step
There are several advantages of creating and initializing an array in one step:
Doing so is less error-prone: the compiler will determine the length of the array, and also the compiler will initialize the elements of the array based on the list you provide. No such thing as using a wrong index value or getting an ArrayIndexOutOfBoundsException.
It will be faster because the JVM (Java Virtual Machine) will not initialize the array with null values.
It will be faster because you don't have to specify explicit index values and the JVM does not have to work with them. Also the JVM does not have to check if indices are in the valid range (that is 0..length-1).
Less maintenance/overhead when later you want to add another element in the middle of the array, you just have to insert it where you want it. Would you have initialized your array the other way, you would have to update all subsequent indices.
The Java source code will be shorter, more compact and also the compiled byte code will be shorter.
You can read more about arrays in the Java Language Specification: Chapter 10. Arrays
The 'new' operator in java is responsible for the creation of new object or we can say instance of a class.
Actually, it dynamically allocates memory in the heap with the reference we define pointed from the stack.

Comparing equals between 1D and 2D array in java

I have two questions:
I am using JAVA programming language and I have found some difficulties using Arrays.
Here are some different arrays :
Object [] play1 = {0,3,6};
Object [] play2 = {0,3,6,4};
Object[][] pre = {{0,1,2},{0,3,6},{2,5,8},{6,7,8},{0,4,8},{2,4,6}};
Question 1 : Is it possible to check equals between play1 and pre using deepEquals? I also know that pre is 2D array and play1 is 1D array.
If I want to check whether play1 is equal to pre, then I might check like:
if(Arrays.deepEquals(pre, play1)){
System.out.print("true");
}else{System.out.print("false");}
Is the code correct? Even though is is possible to check equals between 1D and 2D arrays? Or do I have to use ArrayList? I am not that much familiar with ArrayList. Would appreciate if anyone explain with example.
Question 2 : However, if I want to check between play1 and play2, then also the output is false. I want to check between two arrays even though they don't have equal element but if both array consists the same element such as: {0,3,6} can be found in both play1 and play2, then the output must come true..
Thanks.
For Question2:
You can create List of objects and check as follows:
List<Object> play1List = Arrays.asList(play1);
List<Object> play2List = Arrays.asList(play2);
if(play1List.containsAll(play2List) || play2List.containsAll(play1List))
System.out.println("founD");
For Question1:
List<Object> play1List = Arrays.asList(play1);
for (int i =0 ; i< pre.length;i++){
List<Object> preList = Arrays.asList(pre[i]);
if(preList.equals(play1List)){
System.out.println("FounD"+preList);
break;
}
}
From the API docs:
Two array references are considered deeply equal if both are null, or
if they refer to arrays that contain the same number of elements and
all corresponding pairs of elements in the two arrays are deeply
equal.
From your question I understand that you are searching for a subgroup of the array.
I don't think that there's a function for that on the JDK, probably you have to develop your own function iterating the arrays.

How to find index of int array which match specific value [duplicate]

This question already has answers here:
Why is indexOf failing to find the object?
(3 answers)
Closed 9 years ago.
I have
int myArray[]= {12,23,10,22,10};
So i want to get index of 23 from myArray with out iterating any loop (for ,while ...) .
I would do something like Arrays.asList(myArray).indexOf(23)
This is not work for me . I get -1 as output .
This is work with String[]
Like
String myArray[]= {"12","23","10","22","10"};
Arrays.asList(myArray).indexOf("23")
So why this is not working with int[] ? ?
Integer myArray[]= {12,23,10,22,10};
System.out.println(Arrays.asList(myArray).indexOf(23));
will solve the problem
Arrays.asList(myArray).indexOf(23) this search about objects so we have to use object type of int since int is primitive type.
String myArray[]= {"12","23","10","22","10"};
Arrays.asList(myArray).indexOf("23");
In second case this will work because String is object.
When we define a List,We define it as List<String> or List<Integer>. so primitives are not use in List. Then Arrays.asList(myArray).indexOf("23") find index of equivalent Object.
I concur with Ruchira, and also want to point out that the problem has to do with the fact that int is a primitive while String and Integer are actual objects. (note I would have posted this as a comment but can't until 50 reputation ;) )
If you want to convert an array of primitives to a list of boxed primitives, take advantage of Apache Commons . Once you have the list, as shown below, use the API in List to find object by index.
List<Integer> list = Arrays.asList(ArrayUtils.toObject(myArray));
You can consider keeping your array sorted and use binary subdivision to decide an index. Insert and lookup would both be O(log(n)) in this case (instead of O(1) and O(n) respectively).
If you're doing a lot of looking up you might want to use a different data structure such as a hash map, not just for performance but also because it can be easier to write around.

Categories