Priority queue, Comparable - java

I have to write a priotity queye as implementation of the folowing interface:
public interface PQueue<T extends Comparable<T>> {
public void insert( T o ); // inserts o into the queue
public T remove(); // removes object with highest priority (by natural order)
}
I would be glad for some help and clues, becouse I don't even know how to begin with this issue.

I'd start off with something like this. The general idea is that you have an internal list and when you insert a new item you do a binary search to find where it belongs in that list. This way your internal list is always sorted so when you call remove() you just take the last (or first depending on how you're ordering things) item.
Disclaimer: This should be viewed as pseudo-code. I know for a fact there are problems with it. It's only intended to be a starting point.
public class PQueueImpl<T> implements PQueue<T> {
private List<T> internalQueue;
public void insert(T item){
int insertionPoint = Collections.binarySearch(internalQueue, item);
internalQueue.add(insertionPoint, item);
}
public T remove(){
return internalQueue.remove(internalQueue.size() - 1);
}
}

You could look at the source for java.util.PriorityQueue. Their implementation is backed by an Object array and is significantly more complex than the other example I gave, but I'm sure it works and performs much better too.

Priority queues are in practice implemented most commonly as heaps. They can also be implemented as a balanced binary search tree, or any other fast sorted data structure. The key is that the data structure must have very fast (faster than O(n)) max/min, insert, remove and update operations.

Related

How to change the node in the built-in java LinkedList class to add a right and down pointer?

I have started to use Java. I want to use the built-in Java LinkedList class with my custom node class (my node class will contain fields: data, down pointer, right pointer). Is it possible to do so?
Here is my node class:
public class Node {
int data;
Node rt;
Node dw;
//constructor
public Node(int dataValue) {
rt=null;
dw=null;
data=dataValue;
}
//methods:
public int getData() {
return data;
}
public void setData(int dataValue) {
data = dataValue;
}
public void setrt(Node nextVal) {
rt=nextVal;
}
public void setdw(Node nextVal) {
dw=nextVal;
}
public Node getrt() {
return rt;
}
public Node getdw() {
return dw;
}
I created the following instance:
LinkedList h = new LinkedList<>();
I want to implement a 2D linked list using the built-in linked list class in java. To be able to do this i want to implement my custom node.
No, the node class of LinkedList is private, not exposed, you cannot access it. Except probably through some reflection hack.
And even if you could access the node class, you probably could not replace it with your own class. The LinkedList class is hardcoded to use its own node class.
If you really insisted, you could take the source code of the LinkedList class and modify it to use your node class. Please check if there are any license problems with such an approach before you do it, though. Also my gut feeling is that it’s not worth the trouble compared to writing your custom linked list class from scratch.
Java’s LinkedList is a doubly linked list, so each node has previous and next pointers and reference to data.
You can create a LinkedList of your own for this implementation.
But it looks like there are some basic things which you are doing wrong:
First, as per your implementation, you will be better off with Graph,
because what you are seeking is graph data structure, with each
vertex having four edges.
Second, you should not modify the existing data structures/collection
API provided by Java. If you really want to use different
data-structure, then create it and use it.
And the third and the most important thing to consider is that you
should always try to use the most efficient data-structures to solve a
problem. For example, you can create a 2-D Linkedlist, but ask
yourself, whether is it the most efficient one to store 2-D data? It
might happen that you could have used a matrix or a graph for storing the data.
Also, whenever you create or use a datastructure, consider whether
your application is read/write heavy, based on that you can optimize
storing and fetching of data.
But, it looks like you have just started, and so I would suggest just to go through basic data-structure books or online resources first.
You can also go through below URL which has similar requirement.
custom node class with java's linkedlist class

Data structure which can be sorted with iterator maintaining insertion order

This is a very generalized question, I'll try to be as clear as I can. let's say I have some collection of objects, for simplicity, make them integers. Now I want to make a class which represents these integers as some data structure. In this class I want to implement
a sort function, which sorts the collection according to some defined sorting logic
the iterable interface, where the Iterator traverses in insertion order
How could I make it so that, even if I add integers in unsorted order, e.g.
someCollection.add(1);
someCollection.add(3);
someCollection.add(2);
and then call
Collections.sort(someSortingLogic);
The iterator still traverses in insertion order, after the collection is sorted. Is there a particular data structure I could use for this purpose, or would it be a case of manually tracking which elements are inserted in which order, or something else I can't think of?
Many thanks!
Generally, to solve a problem like this, you maintain two indexes to the values. Perhaps one of those indexes contains the actual values, perhaps both indexes contain the actual values, or perhaps the actual values are stored elsewhere.
Then when you want to walk the sorted order, you use the sorted index to the values, and when you want the insertion order, you use the insert index to the values.
An index can be as simple as an array containing the values. Naturally, you can't store two different values into one spot in an array, so a simple solution is to wrap two arrays in an Object, such that calling the Object's sort() method sorts one array, while leaving the insertion order array untouched.
Fancier data structures leverage fancier techniques, but they all basically boil down to maintaining two orders, the insertion order AND the sort order.
public class SomeCollection {
public void add(int value) {
insertArray = expandIfNeeded(insertArray);
insertArray[insertIndex++] = value;
sortArray = expandIfNeeded(sortArray);
sortArray[sortIndex++] = value;
sort(sortArray);
}
...
}
I'm not sure you've shown us enough code to give you a good answer, but if you have a class that looks a bit like this:
public class Hand implements Iterator<Card>
{
private List<Card> cards = new ArrayList<>();
// Returns iterator for natural ordering of cards
#Override
public Iterator<Card> iterator()
{
return cards.iterator();
}
// Rest of code omitted
Then you can implement a sortedIterator(...) method like this:
// Returns iterator for sorted ordering by Comparator c
public Iterator<Card> sortedIterator(Comparator<? super Card> c)
{
return cards.stream().sorted(c).iterator();
}
If you show us some more code for what you have written, there may be better solutions.

Working With Stack

it has been to long since i asked here ..
I have this homework which has this Q Remove The Bottom Of The Stack I did it
good but not great ..
but now i have a Q is how to reverse the stack i did it by using another stack
is there a better way
this is what i did :
public static<T> void removeLast(LinkedList<T> st)
{
LinkedList<T> store = new LinkedList<>();
while (!st.eamty()){
store.push(st.pop());
}
store.pop();
while(!store.eamty()){
st.push(store.pop());
}
}
some src I found
Most efficient way to reverse a stack and add to an ArrayList
https://www.careercup.com/question?id=12689669
I'd made the following instead:
public static<T> void removeLast(LinkedList<T> st)
{
return st.removeLast();
}
But this is not a queue meant to be used and is also quite "expensive" operation ...
First of all, LinkedList<T> is not just a Stack. It is a List. In fact, it is a list class with a specific operation to removing the last element. (The removeLast method is defined by the Deque interface which LinkedList implements. The Deque abstraction is a "double ended queue"; i.e. something that can act as both a FIFO and a LIFO - a queue and a stack.)
So if you are able to the fact that this representation of a stack is implemented as a linked list, then the solution is to call that method.
On the other hand, if you are required / restricted to implementing your removeLast using only "stack-like" methods in the LinkedList API, then your approach of popping all elements to a temporary stack is probably as good as you can get.

what is a more efficient way to implement enqueue in Java

So I have this simple code in java. It enqueue (adds) and element to the end of the queue (implemented by an ArrayList) without changing the original queue. The code:
public class MyQueue<T>{
private List<T> body;
// some constructors and helper functions.
//copy constructor
public Queue(List<T> list){
this.body = list;
}
//this is the function
public MyQueue<T> enqueue(T obj){
List<T> temp = new ArrayList<T>(body);
temp.add(obj);
return new Queue<T>(temp);
}
The whole Idea is to make enqueue faster and more efficient, and again, as you notice, without changing the value of the original queue.
UPDATE For the sake of completing the idea.
1- This is an assignment so university, the skeleton provided is not to be changed, the task is to make the function enqueue faster (i do realize i am copying twice and thats the slow part).
2- As for the helper functions, they are simple:
public T peek(){
if(body.isEmpty()){
thrown new NoSuchElementException();
}
return body.get(0);
}
public int size(){
return body.size();
}
Any ideas? thanks
A queue is a basic data structure and it's hard to make it better than the experts having worked on it. The simplest and fastest general purpose implementation is probably the ArrayDeque and there's hardly anything to improve.
What you're doing is strange at best:
Instead of appending an element, you copy the whole content. Why?
You insert the new element at the highest index, why? This way your poll (dequeue, remove, whatever) must remove the index at element 0, which is slow for ArrayList.
Actually, I have no idea how your poll may look like. In any case, your enqueue doesn't do what I'd expect from a method called like this.
Use a LinkedList instead of an ArrayList. You don't need indexed access in a queue, but you do need fast enqueue/dequeue. If you need indexed access. It isn't really a queue at all. And just use the add() method, don't create a whole new queue every time. Your enqueue() method should return 'this', or void. And don't allow the caller to supply the list: create your own.

Stack and Hash joint

I'm trying to write a data structure which is a combination of Stack and HashSet with fast push/pop/membership (I'm looking for constant time operations). Think of Python's OrderedDict.
I tried a few things and I came up with the following code: HashInt and SetInt. I need to add some documentation to the source, but basically I use a hash with linear probing to store indices in a vector of the keys. Since linear probing always puts the last element at the end of a continuous range of already filled cells, pop() can be implemented very easy without a sophisticated remove operation.
I have the following problems:
the data structure consumes a lot of memory (some improvement is obvious: stackKeys is larger than needed).
some operations are slower than if I have used fastutil (eg: pop(), even push() in some scenarios). I tried rewriting the classes using fastutil and trove4j, but the overall speed of my application halved.
What performance improvements would you suggest for my code?
What open-source library/code do you know that I can try?
You've already got a pretty good implementation. The only improvement obvious to me is that you do more work than you need to by searching when popping. You should store in the stack not the key itself but the index into the key array. This gives you trivially fast pops at the expense of only one more pointer indirection when you want to peek the last item.
Just size your stack to LOAD_FACTOR*(heap array size), in addition to that, and you should have about as fast an implementation as you could expect with as little memory as you can manage given your speed requirements.
I think that what you want is (almost) already available in the libraries: LinkedHashSet is a hash-set with an underlying doubly linked list (which makes it iterable). LinkedHashMap even has a removeEldestEntry which sounds very similar to a pop-method.
How is the performance of a naive solution like:
class HashStack<T> {
private HashMap<T, Integer> counts = new HashMap<T, Integer>();
private Stack<T> stack = new Stack<T>();
public void push(T t) {
stack.push(t);
counts.put(t, 1 + getCount(t));
}
public T pop() {
T t = stack.pop();
counts.put(t, counts.get(t) - 1);
return t;
}
private int getCount(T t) {
return counts.containsKey(t) ? counts.get(t) : 0;
}
public boolean contains(T t) {
return getCount(t) > 0;
}
public String toString() {
return stack.toString();
}
}
I would suggest using TreeSet<T> as it provides guaranteed O(log n) cost for add, remove, and contains.

Categories