how to find the index of an item in an array java - java

I want to find the index of the start up letter and then show the index of that item in array or array list in java.
Example: I have:
String[] arr={"apple","at","book","bad","car","cat"};
when I input a: then i will get index =0, b: i will get index=2, c: i will get index=4
Because my array item is over 20,000 , so using linear Search is too slow.
and my list is unsorted, so i can't use Binary Search also.
I want to get index of the item like the example above, what can i solve with this?

You can run some initialization code (before the user starts to type letters in).
// initialize an array that has a cell for each letter with value -1
int[] firstIndexes = new int[26];
for(int i=0;i<firstIndexes.length;i++) {
firstIndexes[i] = -1;
}
// loop over original array and look for each letter's first occurence
for(int i=0;i<wordsArray.length;i++) {
char c=wordsArray[i][0];
if(firstIndexes[c-'a'] < 0) {
firstIndexes[c-'a'] = i;
}
}
Then when the user types a letter you just need to find its index in the 'firstIndexes' array.

If you want to get all the indexes of words starting with a certain letter then try this one:
While adding the Words to your Array/list (that will hold all your words) you could also add it to a map that will hold all indexes for every first letters.
Map<String, ArrayList<Integer>> myMap = new HashMap<String, ArrayList<Integer>>();
public void yourmethod() {
//adding all your words to an Array/arraylist goes here. (arr[] in this case)
string firstLetter = yourword.substring(0,1);
if(myMap.constainsKey(firstLetter)) {
myMap.get(letter).add(yourword);
} else {
myMap.put(firstLetter, yourword);
}
}

Related

Returning the contents of an ArrayList index based on if scanner input matches a word inside same index

I am wanting to return the contents of an ArrayList index based on if a scanner input matches any of the words inside said index.
So if ArrayList index 0 contains
<dog, cat, mouse>`
and index 1 contains
<football, baseball, rugby>
and scanner input = "football",
Index 1 in it's entirety should be printed.
However, I am unsure on how to do this so any advice would be fantastic.
Edit:
The code below reads the file where I am getting the data from and stores each separate line as an index.
while (fileScanner.hasNextLine()) {
editList.add(fileScanner.nextLine());
}
The code below reads the input and if editScanner input is found inside the editList, then the index should be printed. However, i know this is incorrect but I am totally unsure on how to print the contents of the index as a String
if (editList.contains(editScanner)) {
while (((edit = fileReader.readLine()) != null)) {
String chosenFilm = editList.indexOf(editScanner);
}
Make your list an arraylist of sets, in this way:
List<Set<String>> yourList = new ArrayList<>();
Then to check if you've to print an index because it has football on it just do
yourList.get(i).contains("football")
If you can't repeat football on various indexes, use a Map instead, using football as the key and the index football is in as the value. Then you can check the index and print that index from the list directly.
Considering your structure is a List<List<String>> and input :
List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("dog", "cat", "mouse"));
list.add(Arrays.asList("football", "baseball", "rugby"));
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
You can do as follow
Iterate over the different subLists and find the good one (stop when you find)
int index = -1;
for (int i = 0; i < list.size(); i++) { // iterate
if (list.get(i).contains(input)) { // check if present
index = i; // keep index
break;
}
}
Using Streams
index = list.stream() // iterate
.filter(l -> l.contains(input)) // keep sublist where present
.mapToInt(list::indexOf) // transform it to its index
.findFirst() // keep index
.orElse(-1); // if not found return -1

Search for a Word in an Array of strings & give its position using Binary Search Technique

The question is to search for a word and give its position using Binary Search Technique. I am accepting all the words in the array and then sorting them using Arrays.sort. Then I use the binarySearch() function to search for a user accepted word but the word's position is not showing correctly.
It's giving random outputs and I can't understand why! there might me something wrong with the way i wrote my for-loop!
I have attached a output screen with multiple outputs.
If anybody could help me that'd be great! Thanks :)
import java.util.*;
import java.util.Arrays;
public class BinarySearch10
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i;
System.out.println("Enter number of words you wish to input: ");
int n=sc.nextInt();
String[] words= new String[n];
System.out.println("Enter the words");
for ( i = 0; i < words.length; i++)
{
System.out.print("WORD " + (i + 1) + ": ");
words[i] = sc.next();
}
System.out.println("enter the word you want to search for");
String word=sc.next();
Arrays.sort(words);
int index= Arrays.binarySearch(words,word);
System.out.println(word+ "="+ index);
}
The output seems to be correct, according to the attached image. After sorting the array alphabetically (using Array.sort()), the order of the elements will be:
are, hello, how, you.
The index of "you" is 3, as in the output. Same for the second example, where the index of "are" is 0.
You are getting random values because you are sorting the array first,
After sorting the indexes are changed
Because Arrays.sort is an in-place sorting. It means that when you sort the words, their positions have been changed: the new order will be the lexicographical (alphabetical) order. Here's an example:
// before the sort
// words = ["word-b", "word-c", "word-a"]
Arrays.sort(words);
// after the sort
// words = ["word-a", "word-b", "word-c"]
As you see, word word-c has changed its position from index 1 to index 2.
Solution 1
A simple solution is to avoid using sort and binary search here. You can find the word using a for loop:
for (int i = 0; i < words.length; i++) {
if (searchWord.equals(words[i])) {
// word found at index i
}
}
Solution 2
If you want to continue your work using sort, you need to use a Map to store the initial position (index) of each word: the key of the map is the word, the value of the map is the word initial index.

How to get index of value in array?

I have an array like this :
String[] array = { "Designation1", "Designation2", "Designation3" };
If user put "Designation2" as input then the code should return 1.
It may be very simple question, but I am very new in Java. So please give some suggestions.
Consider using List instead of array (of just wrap your array in List). This way you will have access to method like indexOf(element) which will return index of first founded element, of -1 if no element in array was found.
String[] array = { "Designation1", "Designation2", "Designation3" };
List<String> list = Arrays.asList(array);
System.out.println(list.indexOf("Designation2")); //prints 1
System.out.println(list.indexOf("foo")); //prints -1
You can loop over the Strings in the array and find the index for which the String matches what you are looking for.
int index = -1;
for (int i=0; i<array.length;i++) {
if (array[i].equals(value)) {
index = i;
break;
}
}
You could just use a for loop
String[] array = { "Designation1", "Designation2", "Designation3" };
Scanner kb=new Scanner(System.in);
String input=kb.next();
int index;
for(int i=0;i<array.length;i++)
{
if(array[i].equalsIgnoreCase(input))
index=i;
}
You can do it like this.
String userinput="Designation2";
String[] array = { "Designation1", "Designation2", "Designation3" };
int length=array.length();
int index=0;
for(int i=0;i<length;i++)
{
if(array[i].equals(userinput))
{
index=i;
break;
}
}
And index will give you the array key that user wants.
Regards..
There are no direct search method for array so you need to convert it to list first
String[] array = { "Designation1", "Designation2", "Designation3" };
assert Arrays.asList(array).indexOf("Designation2") == 1;
assert Arrays.asList(array).indexOf("Anything else") == -1;
Do not forget that -1 mean 'not found'
Or you can sort it and use binarySearch
You can use ArrayUtils from Apache Commons.
String[] array = { "Designation1", "Designation2", "Designation3" };
System.out.println(ArrayUtils.indexOf(array, "Designation1"));//0
System.out.println(ArrayUtils.indexOf(array, "Designation2"));//1
System.out.println(ArrayUtils.indexOf(array, "Designation3"));//2
In order to do this task, you can use two arrays, one for key names and ones for their values. Simply search for the key in the first array, get the index of the key name and use it to get the value from the second array. It's not the most efficient, and this is probably not the best answer, but it works for me.
Just make sure the indexes in the arrays line up, for example:
{"my","three","keys"};
{"My","Three","Values"};
In this case, the key/value setup would be;
my/My
three/Three
keys/Values
In your case, you don't need to use the value array, just use the index.
Also try using ArrayList instead of arrays, as you can use ArrayList.indexOf(key) to get the index of key in the ArrayList.
Hope this helps you and others with this problem. ☺

Issue when iterating through lists: IndexOutOfBoundsException in Java

I'm writing a program that applies many principles of computational linguistics. My problem at this moment is the following piece of code form a method that "flexibilizes two definitions". This is, it compares two different definitions of the same word, and in each definition empty or blank spaces will be added to later on work with the altered definitions (with blank spaces added).
Say we have the following two definitions, defining the term "free fall".
1) Free fall descent of a body subjected only to the action of gravity.
2) Free fall movement of a body in a gravitational field under the influence of gravity
There is a list of words called stoplist, which contains the words: "of", "a", "in", "to", and "under". After the process, each word in the definition that is also contained in the stoplist must correspond to a blank space OR another stoplist word of the other definition. So after executing such process, the previous definitions, represented in two different lists, should look like this:
1) Free fall descent of a body ____ ____ subjected only to the action of gravity.
2) Free fall movement of a body in a gravitational field under the influence of gravity.
The code I wrote to achieve this is the following:
[...]
String[] sList = STOPLIST.split(" "); //this is the stoplist
String[] definition1 = defA1.split(" "); //this is the array of words of the first definition
String[] definition2 = defA2.split(" "); //this is the array of words of the second definition
List<String> def1 = new ArrayList<String>();
List<String> def2 = new ArrayList<String>();
List<String> stopList = new ArrayList<String>();
for(String word : definition1){
def1.add(word); //I transform arrays into lists this way because I used to think that using .asList() was the problem.
}
for(String word : definition2){
def2.add(word);
}
for(String word : sList){
stopList.add(word);
}
int mdef = (def1.size() <= def2.size()) ? def1.size() : def2.size(); //here mdef will have the value of the lenght of the shortest definition, and we are going to use the value of mdef to iterate later on.
for(int i = 0; i < mdef; i++){
if (stopList.contains(def1.get(i))) { //here I check if the first word of the first definition is also found in the stoplist.
if (!stopList.contains(def2.get(i))) { //If the word of def1 previously checked is in the stoplist, as well as the corresponding word in the second definition, then we won't add a " "(blank) space in the corresponding position of the second definition.
def2.add(i , " "); //here I add that blank space, only if the stoplist word in def1 corresponds to a non-stoplist word in def2. Again, we do this so the stoplist word in def1 corresponds to a blank space OR another stoplist word in def2.
if(mdef == def2.size())
mdef++; //In case the shortest definition is the definition to which we just added spaces, we increment mdef++, because that space added increases the length of the shortest definition, and to iterate in this recenlty extended definiton, we have to increment the index with which we iterate.
}
} else if (stopList.contains(def2.get(i))) { //this else if does the same than the previous one, but checks for the second definition instead of the first one. And adds blanks to def1 instead of def2 if necessary.
if (!stopList.contains(def1.get(i))) {
def1.add(i , " ");
if(mdef == def1.size())
mdef++;
}
}
}
[...]
Now, if you analyze the code carefully, you will realize that not all words of the lengthiest list will be checked, given that we iterate ove the definitions using the lenght of the shortest definition as index. This is fine, the remainding words of the lenghtiest definitions don't have to be checked, they will correspond to null spaces of the other definition (in case the lists don't end up being of the same lenght after the addition of spaces, as the previous exaple shows).
Now, after the explanation, the problem is the following: after running the main class, which calls the method that contains the previous code, a runtime exceptions pops out:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:571)
at java.util.ArrayList.get(ArrayList.java:349)
at main2.main(main2.java:75)
I don't understand why it is finding any of the lists as "empty". I have tried to solve it in too many ways, I hope a I gave a good explanation.
It may help as a clue that if I assign mdef to the lengthiest size instead of the shortest, that is :
int mdef = (def1.size() >= def2.size()) ? def1.size() : def2.size();
the error changes to:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 15
at java.util.ArrayList.rangeCheck(ArrayList.java:571)
at java.util.ArrayList.get(ArrayList.java:349)
at asmethods.lcc.turnIntoFlex(lcc.java:55)
at asmethods.lcc.calLcc(lcc.java:99)
at main2.main(main2.java:73)'
Where lcc is the class that contains the method turnIntoFlex that contains the piece of code I'm showing. The line 55 of "turnIntoFlex" corresponds to the first line of the loop, that is:
if (stopList.contains(def1.get(i))) { [...]
Comments: The values of defA1 and defA2 are the definitions, respectively. i.e. def1 and def2, initially, are lists in which each separate element is a word. I can't check if these lists are being populated by printing them because the indexoutofboundsexception pops at the very moment the loop starts. However, I do print the values of the sizes of mdef, def1.size() and def2.size(), and the values turn out to be 13, or 15, showing that no list is empty before the "for" loop starts.
The mdef++ was something I added recently, not to exactly to solve this specific problem, but the error has been popping since before I added the mdef++ part. As I explained, The intention is to increase mdef++ when the shortest list is extended (but only when the short list is extended) so we iterate through all the words of the short list, and not more.
One issue with your code is that when you increment mdef you do not check to see if it now exceeds the length of the other list.
For example, suppose def1 had 3 words and def2 had 4 words. mdef would start at 3. But then suppose you successively add two spaces to def1 and increment mdef twice to be 5. This now exceeds the length of def2 and will then cause an index out of bounds exception in the def2 else condition if you keep iterating up to 5.
Added later:
Another serious issue with your code (that I thought of later) is that when you add the space to a list (either def1 or def2) this shifts the indices of all of the subsequent elements up by 1. So, for example, if you add a space at spot 0 in def1 when i is 0, then on the next pass through the loop, having incremented i to 1, you will look at the same word in def1 that you looked at in the previous pass. This is probably the source of some of your exceptions (as it would lead to a continual loop until you exceed the length of the other list: problem #1 above).
To correct both of these issues, you would need to change your code to something like:
int i = 0;
int j = 0;
while (i < def1.size() && j < def2.size()) {
if (stopList.contains(def1.get(i)) && !stopList.contains(def2.get(j)))
def2.add(j++, " ");
else if (stopList.contains(def2.get(j)) && !stopList.contains(def1.get(i)))
def1.add(i++, " ");
++i;
++j;
}
Note that you don't ned mdef any more in this implementation.
Man, I think I got it. I modified the code, but I hope you understand what I did:
static public void main(String[] argv) {
String[] sList = "of a in to under".split(" ");
String[] definition1 = "Free fall descent of a body subjected only to the action of gravity"
.split(" ");
String[] definition2 = "Free fall movement of a body in a gravitational field under the influence of gravity"
.split(" ");
List<String> def1 = new ArrayList<String>();
List<String> def2 = new ArrayList<String>();
List<String> stopList = new ArrayList<String>();
for (String word : definition1) {
def1.add(word);
}
for (String word : definition2) {
def2.add(word);
}
for (String word : sList) {
stopList.add(word);
}
int mdef = (def1.size() <= def2.size()) ? def1.size() : def2.size(); // Shortest
// length
for (int i = 0; i < mdef; i++) {
System.out.println(i);
if (!stopList.contains(def1.get(i)) && !stopList.contains(def2.get(i))) {
continue;
}
else if (stopList.contains(def1.get(i)) && stopList.contains(def2.get(i))) {
continue;
}
else if (!stopList.contains(def1.get(i)) && stopList.contains(def2.get(i))) {
def1.add(i, " ");
mdef = (def1.size() <= def2.size()) ? def1.size() : def2.size(); // define mdef again
}
else if (stopList.contains(def1.get(i)) && !stopList.contains(def2.get(i))) {
def2.add(i, " ");
mdef = (def1.size() <= def2.size()) ? def1.size() : def2.size(); // define mdef again
}
}
for (String word : def1) {
if (word.equals(" "))
System.out.print("_ ");
else
System.out.print(word+" ");
}
System.out.println();
for (String word : def2) {
if (word.equals(" "))
System.out.print("_ ");
else
System.out.print(word+" ");
}
}
Is this the exact code you're using? I just ran it and it worked fine, I used:
import java.util.*;
public class HelloWorld {
public static void main(String []args) {
String stoplist= "of a in to and under";
String defA1 = "Free fall descent of a body subjected only to the action of gravity";
String defA2 = "Free fall movement of a body in a gravitational field under the influence of gravity";
String[] sList = stoplist.split(" "); //this is the stoplist
String[] definition1 = defA1.split(" "); //this is the array of words of the first definition
String[] definition2 = defA2.split(" "); //this is the array of words of the second definition
List<String> def1 = new ArrayList<String>();
List<String> def2 = new ArrayList<String>();
List<String> stopList = new ArrayList<String>();
for (String word : definition1) {
def1.add(word); //I transform arrays into lists this way because I used to think that using .asList() was the problem.
}
for (String word : definition2) {
def2.add(word);
}
for (String word : sList) {
stopList.add(word);
}
int mdef = (def1.size() <= def2.size()) ? def1.size() : def2.size(); //here mdef will have the value of the lenght of the shortest definition, and we are going to use the value of mdef to iterate later on.
for (int i = 0; i < mdef; i++) {
if (stopList.contains(def1.get(i))) { //here I check if the first word of the first definition is also found in the stoplist.
if (!stopList.contains(def2.get(i))) { //If the word of def1 previously checked is in the stoplist, as well as the corresponding word in the second definition, then we won't add a " "(blank) space in the corresponding position of the second definition.
def2.add(i , " "); //here I add that blank space, only if the stoplist word in def1 corresponds to a non-stoplist word in def2. Again, we do this so the stoplist word in def1 corresponds to a blank space OR another stoplist word in def2.
if (mdef == def2.size())
mdef++; //In case the shortest definition is the definition to which we just added spaces, we increment mdef++, because that space added increases the length of the shortest definition, and to iterate in this recenlty extended definiton, we have to increment the index with which we iterate.
}
} else if (stopList.contains(def2.get(i))) { //this else if does the same than the previous one, but checks for the second definition instead of the first one. And adds blanks to def1 instead of def2 if necessary.
if (!stopList.contains(def1.get(i))) {
def1.add(i , " ");
if (mdef == def1.size())
mdef++;
}
}
}
for (String word : def1) {
System.out.print(word+",");
}
System.out.println();
for (String word : def2) {
System.out.print(word+",");
}
}
}

Android listView ArrayList similar Search

I use ArrayList for my Dictionary Index Data
I want to make similar search system
for example
dictionary data : 'abcd' 'bcde' 'cdef' 'fghi' 'ijkl'
if i search 'cd' i want to get index '3'
in my source
for (String st : wordList) {
if (st.indexOf(searchWord) == 0) {
ListView.setSelection(index); //set listView scroll
break;
}
index++;
}
but it took too much time :(
what is the best way to make this system?
just remove index++ from loop and change if(CONDITION) like this.
for (String st : wordList) {
if (st.startsWith(searchWord)) {
System.out.println("position="+wordlist.indexOf(st));//display index in log
ListView.setSelection(wordlist.indexOf(st)); //set listView scroll
break;
}
}
Divide and Rule :)
Rather than storing all dictionary data into single list .... create array list for each Char like a,b,c,d (you will have total 26 list : one is for each alphabet)
Map<Character, List<String>> map = new HashMap<Character, List<String>>();
// creating list for each char
for(int i=0;i<26;i++){
char ch = (char) ('a' + i);
map.put(ch,new ArrayList<String>());
}
// storing some sample dictionary data or make a function for it
map.get("abcd".charAt(0)).add("abcd");
map.get("bcde".charAt(0)).add("bcde");
map.get("cdef".charAt(0)).add("cdef");
map.get("fghi".charAt(0)).add("fghi");
map.get("ijkl".charAt(0)).add("ijkl");
String searchWord = "cd";
// searh the given String
List<String> wordList =map.get(searchWord.charAt(0));
int idx =0;
for (String st : wordList) {
if (st.startsWith(searchWord)) {
idx = wordList.indexOf(st);
System.out.println("position="+idx); //display index in log
break;
}
}
// if require, In idx variable : add the size() of all list
// which come before the give searh char
// ListView.setSelection(idx); //set listView scroll
}
Note : please convert the upper case word to lower case before searching or storing.

Categories

Resources