I have a string array where I want to check each element in the array with 8 other array elements to see if any of those element in the first array element categorize under any of them.
Simply I want to categorize a string array. So in order to do that I have to check with 8 other arrays (Because I have 8 categories) I want to know an efficient way to do this without looping one by one
You can use HashMap instead of array or arraylist.
Implement the 8 categories as HashMap.
From the element you want to check, match it against the the 8 HashMaps. This will give you a worst case of 8 checks.
If you can combine the values of all 8 categories into one HashMap, the worst case will be 1.
I believe you could combine the values from various categories and have only 1 HashMap by appending a checksum to each value. Something like:
//values in the hash map
xxxx_cat1
yyyy_cat1
zzzz_cat1
xxxx_cat2
yyyy_cat2
zzzz_cat2
After you get the value from the HashMap, just based on the checksum (the appended text) to get its category.
You can sort the array and then use Arrays.binarySearch() method instead of looping one by one. It is more efficient way to search a particular element.
Related
so i have an array list that contains strings such as:
ArrayList<String> list = new ArrayList<>();
list.add("bookshelf");
list.add("bookstore");
list.add("library");
list.add("pencil");
Now i wanna search and remove all the strings in the arraylist that contain the word "book" in them. As far as i understand list.remove("book"); will only search for the particular string "book" and not the strings that contain the word "book". How can i solve this?
You can use removeIf like this:
list.removeIf(s -> s.contains("book"));
Note: this answers applies to Java version 7 and below (of course that it will work for higher versions as well but YCF_L's answer is simpler to implement in versions 8 and above).
The requirement is to iterate the list, check every element, and if it answers a certain condition: remove it.
Since this is the case we fall into a risky scenario where we modify the list while iterating it which is problematic because when we remove an element in the list its size changes.
In order to work around this problem we can iterate the list by index from the last element and back until the first one, this way, removing an element at index n will not effect accessing any element at index < n.
I'll leave the implementation details to you in order not to "spoon feed" and destroy your exercise :)
I have a 2D array called distance[][]
It holds my values in column 0:
Example:
{ 5
7
3
9 }
It seems like a 1D array, however I've converted it into a 2D array in order to be able to keep track of my indexes.
The way I access my first value is distance[0][0].
My question is: how can I keep track of the original index positions if I were to sort my array. I was under the impression that I may need to create a corresponding list of numbers in ascending order which correspond with the position my of distance values.
What would I do after that?
All you need is to use comparator. Consider below code -
Arrays.sort(arr, new java.util.Comparator<int[]>(){
public int compare(int[] a,int[] b){
return a[0]-b[0];
}
});
arr is your orginial 2d array, where first column contains the number to sorted and second column contains index
The simplest solution would be to create a Pair class that holds the item and its corresponding index.Then, keep a list of this Pair classes int two different lists and than sort one of them.Since in java, you can use references without creating a copy object,this should be fairly easy.Now the sorted list will contain the values and its corresponding indices sorted according to the value and the unsorted list will have the Pair sin the order you entered them, that is ,sorted according to the index.
I am currently making a tiny little program that should be able to select a random element i put into the array using a Random of course (For practice purposes) and when a element in the array has been chosen at random. i want to remove this element in the array, so how do you remove a element in a array the easiest way?
Its the only thing i want to know. I got everything else sorted. It's just removing the element it has chosen (the random takes a random number between 0 and the amount of elements in the array, so if it chooses 0, it will take the first element in the array, and so on)
You can use ArrayList which support remove or add function, which actually is an resizable array.
You can't remove an element from an array. You can replace it with some other value that indicates "nothing", null for example.
An easy solution is to convert the array into a list.
list = Arrays.asList(array);
Remove any element from the list and then revert it back to an array using
array = list.toArray();
Hope it helps.
Use List instead of Array, and if you want to stay on Array than there is 2 solution,
Create another Array ignoring your element which you want to delete.
create a List using Array.asList(...) than remove element from list and convert back to Array.
but according to me its better for you as well as java to use List. because List provide a many build-in functions.
I have an ArrayList which I fill with objects of type Integer in a serial fashion (i.e. one-by-one) from the end of the ArrayList (i.e. using the method add(object)). Every time I do this, the other objects in the ArrayList are of course left-shifted by one index.
In my code I want to find the index of a random object in the ArrayList. I want to avoid using the indexOf method because I have a very big ArrayList and the looping will take an enormous amount of time. Are there any workarounds? Some idea how to keep in some data structure maybe the indexes of the objects that are in the ArrayList?
EDIT: Apparently my question was not clear or I had a missunderstanding of the arraylist.add(object) method (which is also very possible!). What I want to do is to have something like a sliding-window with objects being inserted at one end of the arraylist and dropped from the other, and as an object is inserted to one end the others are shifted by one index. I could use arraylist.add(0, object) for inserting the objects from the left of the arraylist and right-shifting each time the previous objects by one index, but making a google search I found that this is very processing-intensive operation - O(N) if I remember right. Thus, I thought "ok, let's insert the objects from the right-end of the arraylist, no problem!", assuming that still each insertion will move the previous objects by one index (to the left this time).
Also when I use the term "index" I simply mean the position of the object in the ArrayList - maybe there is some more formall term "index" which means something different.
You have a couple of options. Here are the two basic options:
You can maintain a Map<Object,Integer> that holds indexes, in parallel to the array. When you append an element to the array you can just add it to the map. When you remove an element from the beginning you will have to iterate through the entire map and subtract one from every index.
If it's appropriate for your situation and the Map does not meet your performance requirements, you could add an index field to your objects and store the index directly when you add it to the array. When you remove an element from the beginning you will have to iterate through all objects in the list and subtract one from their index. Then you can obtain the index in constant time given an object.
These still have the performance hit of updating the indexes after a remove. Now, after you choose one of these options, you can avoid having to iterate through the map / list to update after removal if you make a simple improvement:
Instead of storing the index of each object, store a count of the total number of objects added so far. Then to get the actual index, simply subtract the count value of the first object from the value of the one you are looking for. E.g. when you add:
add a to end;
a.counter = counter++;
remove first object;
(The initial value of counter when starting the program doesn't really matter.) Then to find an object "x":
index = x.counter - first object.counter;
Whether you store counter as a new field or in a map is up to you. Hope that helps.
By the way; a linked list will have better performance when removing object from the front of the list, but worse when accessing an object by index. It may be more appropriate depending on your balance of add/remove vs. random access (if you only care about the index but never actually need to retrieve an object by index, random access performance doesn't matter). If you really need to optimize further you could consider using a fixed-capacity ring buffer instead (back inserts, front removes, and random access will all be O(1)).
Of course, option 3 is to reconsider your algorithm at a higher level; perhaps there is a way to accomplish the behavior you are seeking that does not require finding the objects in the list.
I need a data structure that supports the following operations in O(1):
myList.add(Item)
myList.remove(Item.ID) ==> It actually requires random access
myList.getRandomElement() (with equal probability)
--(Please note that getRandomElement() does not mean random access, it just means: "Give me one of the items at random, with equal probability")
Note that my items are unique, so I don't care if a List or Set is used.
I checked some java data structures, but it seems that none of them is the solution:
HashSet supports 1,2 in O(1), but it cannot give me a random element in O(1). I need to call mySet.iterator().next() to select a random element, which takes O(n).
ArrayList does 1,3 in O(1), but it needs to do a linear search to find the element I want to delete, though it takes O(n)
Any suggestions? Please tell me which functions should I call?
If java does not have such data structure, which algorithm should I use for such purpose?
You can use combination of HashMap and ArrayList if memory permits as follows:-
Store numbers in ArrayList arr as they come.
Use HashMap to give mapping arr[i] => i
While generating random select random form arrayList
Deleting :-
check in HashMap for num => i
swap(i,arr.size()-1)
HashMap.remove(num)
HashMap(arr[i])=> i
arr.remove(arr.size()-1)
All operation are O(1) but extra O(N) space
You can use a HashMap (of ID to array index) in conjunction with an array (or ArrayList).
add could be done in O(1) by simply adding to the array and adding the ID and index to the HashMap.
remove could be done in O(1) by doing a lookup (and removal) from the HashMap to find the index, then move the last index in the array to that index, update that element's index in the HashMap and decreasing the array size by one.
getRandomElement could be done in O(1) by returning a random element from the array.
Example:
Array: [5,3,2,4]
HashMap: [5->0, 3->1, 2->2, 4->3]
To remove 3:
Look up (and remove) key 3 in the HashMap (giving 3->1)
Swap 3 and, the last element, 4 in the array
Update 4's index in the HashMap to 1
Decrease the size of the array by 1
Array: [5,4,2]
HashMap: [5->0, 2->2, 4->1]
To add 6:
Simply add it to the array and HashMap
Array: [5,4,2,6]
HashMap: [5->0, 2->2, 4->1, 6->3]