How to delete a specific element from a priority queue? - java

I have created a priority queue using the Java API and I want to remove a specific element from the priority queue at the end of the program. I know it has to do something with the comparator but I can't figure it out. Can someone help? Here's my code:
public static void main(String[] args)
{
PriorityQueue<Element> X = new PriorityQueue<Element>(100, new ElementComparator());
X.add(new Element(30, 3));
X.add(new Element(700, 4.5));
X.add(new Element(100, 6.2));
X.add(new Element(2, 8.1));
System.out.println(X.remove(new Element(100, 6.2)));
}
and here's my Element class:
private int index;
private double value;
public Element(int i, double v)
{
index = i;
value = v;
}
public int getIndex() { return index;};
public double getValue() { return value;};
public void setValue(double v) { value = v;};
And here's the comparator that I created:
public int compare(Element o1, Element o2)
{
int idx1 = o1.getIndex();
int idx2 = o2.getIndex();
if (idx1 < idx2) {
return -1;
} else if (idx1 > idx2) {
return 1;
} else {
return 0;
}
}
public boolean equals(Element o1, Element o2)
{
return o1.getIndex() == o2.getIndex();
}
I appreciate your help...

You need to define equals() and hashcode() on your Element object as such:
public class Element{
private int index;
private double value;
public Element(int i, double v)
{
index = i;
value = v;
}
public int getIndex() { return index;}
public double getValue() { return value;}
public void setValue(double v) { value = v;}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Element)) return false;
Element element = (Element) o;
if (index != element.index) return false;
return true;
}
#Override
public int hashCode() {
return index;
}
}
Defining equals() on the ElementComparator does not perform the same task.

Related

How do you use a custom comparator for priority queues?

I'm trying to implement a priority queue that compares Nodes that have a "cost" value. I have tried 3 implementations of comparators and none of them have worked.
Node def:
public class Node implements Comparable<Node>{
int[][] data;
int x, y;
int cost;
Node parent;
Node (int[][] data, int x, int y, int newX, int newY, Node parent) {
this.parent = parent;
//SWAPS VALUE
int temp = data[newX][newY];
data[newX][newY] = data[x][y];
data[x][y] = temp;
this.cost = Integer.MAX_VALUE;
this.x = newX;
this.y = newY;
}
public int compareTo(Node otherNode) {
if (this.cost < otherNode.cost) {
return -1;
} else if (this.cost > otherNode.cost) {
return 1;
} else {
return 0;
}
}
}
First Comparator:
Comparator<Node> CustomComp = new Comparator<Node>() {
#Override
public int compare(Node lhs, Node rhs) {
return lhs.compareTo(rhs);
}
};
Second Comparator:
Comparator<Node> CustomComp2 = (Node lhs, Node rhs) -> {
return lhs.compareTo(rhs);
};
Third Comparator:
public class NodeComparator implements Comparator<Node> {
#Override
public int compare(Node lhs, Node rhs) {
if (lhs.cost < rhs.cost) {
return -1;
} else if (lhs.cost > rhs.cost) {
return 1;
} else {
return 0;
}
}
}
Priority Queue Implementation:
PriorityQueue<Node> pq = new PriorityQueue<Node>(11, comp);
this implementation was after attempting to use the last one
This is also my first question here, and thanks in advance!
EDIT:
This is the error it gives for new PriorityQueue<Node>(11, comp)
The constructor PriorityQueue<main.Node>(int, main.Comparator<main.Node>) is undefined
There is no output currently but it should store nodes for later use in a tree.

Did I mess up a constructor/method in this?

I don't get what is wrong. Something defintely is. I am just a noob. The idea is I put in all these parameters and run it on the TestMyInteger class. I am getting a major error Exception in thread "main" java.lang.NoClassDefFoundError: MyInteger
at TestMyInteger.main(TestMyInteger.java:3)
Caused by: java.lang.ClassNotFoundException: MyInteger
I can't figure out what is wrong with my code
public class MyInteger {
private int value;
public MyInteger (int value) {
this.value = value;
} //myInteger
public int getValue() {
return value;
}//getValue
public boolean isEven() {
return (value % 2 == 0);
}//isEven(not static)
public boolean isOdd() {
return (value % 2 != 0);
}//isOdd(not static)
public boolean isPrime() {
int i = 0;
for(i = 2; i <= value / 2; i++){
if(value % i != 0)
return true;
}
return false;
}//isPrime (not static)
public static boolean isEven (int n) {
return (n % 2 == 0);
}//isEven(static)
public static boolean isOdd(int n) {
return (n % 2 != 0);
}//isOdd(static)
public static boolean isPrime(int n) {
int i = 0;
for(i = 2; i <= n / 2; i++){
if(n % i != 0)
return true;
}
return false;
}//isPrime(static)
public static boolean isEven(MyInteger n) {
return n.isEven();
}// myInteger isEven
public static boolean isPrime(MyInteger o) {
int i = 0;
for(i = 2; i <= o / 2; i++){
if(o % i != 0)
return true;
}
return false;
} //myInteger prime
public static boolean isOdd(MyInteger o) {
return (o % 2 != 0);
}//MyInteger isOdd
public boolean equals(int anotherNum) {
if (n1 == n2)
return true;
return false;
} //what value is this (equals)
public boolean equals(MyInteger o) {
if (n1 == n2)
return true;
return false;
`enter code here` }//MyInteger equals
}
All of this will be run on this TestMyInteger class
public class TestMyInteger {
public static void main(String[] args) {
MyInteger n1 = new MyInteger(5);
System.out.println("n1 is even? " + n1.isEven());
System.out.println("n1 is prime? " + n1.isPrime());
System.out.println("15 is prime? " + MyInteger.isPrime(15));
System.out.println("15 is even? " + MyInteger.isEven(15));
MyInteger n2 = new MyInteger(24);
System.out.println("n2 is odd? " + n2.isOdd());
System.out.println("45 is odd? " + MyInteger.isOdd(45));
System.out.println("n1 is equal to n2? " + n1.equals(n2));
System.out.println("n1 is equal to 5? " + n1.equals(5));
System.out.println("n2 is even? " + MyInteger.isEven(n2));
System.out.println("n2 is odd? " + MyInteger.isOdd(n2));
System.out.println("n2 is prime? " + MyInteger.isPrime(n2));
}
}//TestMyInteger
Delegate, don't re-implement the same methods over and over. In order to access the value from a MyInteger instance you need to use instance.value. Your isPrime logic appears to be inverted. Don't try and change the signature of Object.equals(Object). If you plan to override equals, you should override hashCode and toString as well. Like,
public class MyInteger {
private int value;
public MyInteger(int value) {
this.value = value;
} // myInteger
public int getValue() {
return value;
}// getValue
public boolean isEven() {
return isEven(value);
}// isEven(not static)
public boolean isOdd() {
return isOdd(value);
}// isOdd(not static)
public boolean isPrime() {
return isPrime(value);
}// isPrime (not static)
public static boolean isEven(int n) {
return (n % 2 == 0);
}// isEven(static)
public static boolean isOdd(int n) {
return !isEven(n);
}// isOdd(static)
public static boolean isPrime(int n) {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}// isPrime(static)
public static boolean isEven(MyInteger n) {
return isEven(n.value);
}// myInteger isEven
public static boolean isPrime(MyInteger o) {
return isPrime(o.value);
} // myInteger prime
public static boolean isOdd(MyInteger o) {
return isOdd(o.value);
}// MyInteger isOdd
public boolean equals(int anotherNum) {
return value == anotherNum;
} // what value is this (equals)
#Override
public boolean equals(Object o) {
if (o instanceof MyInteger) {
return equals(((MyInteger) o).value);
}
return false;
}// MyInteger equals
#Override
public int hashCode() {
return Integer.hashCode(value);
}
#Override
public String toString() {
return String.valueOf(value);
}
}
Until you can compile MyInteger, you can't use MyInteger. The computer doesn't know how.
public final class MyInteger {
private final int value;
public MyInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean isEven() {
return isEven(value);
}
public boolean isOdd() {
return isOdd(value);
}
public boolean isPrime() {
return isPrime(value);
}
public static boolean isEven(int value) {
return value % 2 == 0;
}
public static boolean isOdd(int value) {
return !isEven(value);
}
public static boolean isPrime(int value) {
if (Math.abs(value) < 2)
return false;
for (int i = 2, max = (int)Math.sqrt(value); i <= max; i++)
if (value % i == 0)
return false;
return true;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
return obj instanceof MyInteger && value == ((MyInteger)obj).value;
}
#Override
public int hashCode() {
return Objects.hash(value);
}
#Override
public String toString() {
return String.valueOf(value);
}
}

mostFrequent method bags adt(abstract data types)

I am trying to implement a method named mostFrequent in a bag that finds the most frequent object in a bag For example, if B = {Bob, Joe, Bob, Ned, Bob, Bob}, then the method
returns Bob. Hint: The method is O(n^2).
public E MostFrequent (Bag<E> B){
// implementation here
}
The adt of the bag is the following:
package edu.uprm.ece.icom4035.bag;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StaticBag implements Bag {
private int currentSize;
private Object elements[];
private class BagIterator implements Iterator {
private int currentPosition;
public BagIterator(){
this.currentPosition = 0;
}
#Override
public boolean hasNext() {
return this.currentPosition < currentSize;
}
#Override
public Object next() {
if (hasNext()){
return elements[this.currentPosition++];
}
else {
throw new NoSuchElementException();
}
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public StaticBag(int maxSize){
if (maxSize < 1){
throw new IllegalArgumentException("Max size must be at least 1.");
}
this.currentSize = 0;
this.elements = new Object[maxSize];
}
#Override
public void add(Object obj) {
if (obj == null){
throw new IllegalArgumentException("Value cannot be null.");
}
else if (this.size() == this.elements.length){
throw new IllegalStateException("Bag is full.");
}
else {
this.elements[this.currentSize++] = obj;
}
}
#Override
public boolean erase(Object obj) {
int target = -1;
for (int i=0; i < this.size(); ++i){
if (this.elements[i].equals(obj)){
target = i;
break;
}
}
if (target == -1){
return false;
}
else {
this.elements[target] = this.elements[this.currentSize-1];
this.elements[this.currentSize-1] = null;
this.currentSize--;
return true;
}
}
#Override
public int eraseAll(Object obj) {
int copies = 0;
while(this.erase(obj)){
copies++;
}
return copies;
}
#Override
public int count(Object obj) {
int counter = 0;
for (int i=0; i < this.size(); ++i){
if (elements[i].equals(obj)){
counter++;
}
}
return counter;
}
#Override
public void clear() {
for (int i=0; i < this.size(); ++i){
this.elements[i] = null;
}
this.currentSize = 0;
}
#Override
public boolean isEmpty() {
return this.size() == 0;
}
#Override
public int size() {
return this.currentSize;
}
#Override
public boolean isMember(Object obj) {
return this.count(obj) > 0;
}
#Override
public Iterator iterator() {
return new BagIterator();
}
}
the method must be implemented in the most efficient way and if possible using the methods already given in the bag adt
What I've been trying is the following:
public E MostFrequent(Bag<E> B){
for(E e : B){
int counter = B.count(e)
}
}
but I don't seem to think of a way to return the object with more frequencies inside the loop

Java Hashtable Chaining

I am supposed to write a Java Hashtable function being able to import java.util.Iterator, java.util.NoSuchElementException, and java.util.ConcurrentModificationException. There is no specific on what type of Hashing function to use. SO how do I write my getHashCode function. My code so far:
package data_structures;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import data_structures.LinkedListDS.IteratorHelper;
public class Hashtable<K,V> implements DictionaryADT<K,V> {
private int currentSize,maxSize,tableSize;
private long modCounter;
private LinkedListDS <DictionaryNode<K,V>> [] list;
class DictionaryNode<K,V> implements Comparable<DictionaryNode<K,V>> {
K key;
V value;
public DictionaryNode(K k, V v) {
key = k;
value = v;
}
public int compareTo(DictionaryNode<K,V> node) {
return ((Comparable<K>)key).compareTo((K)node.key);
}
}
public Hashtable(int n) {
currentSize = 0;
maxSize = n;
modCounter = 0;
tableSize = (int) (maxSize * 1.3f);
list = new LinkedListDS[tableSize];
for (int i=0; i < tableSize; i++)
list[i] = new LinkedListDS<DictionaryNode<K,V>>();
}
public boolean contains(K key) {
return list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null));
}
private int getHashCode(K key) {
// TODO Auto-generated method stub
return 0;
}
public boolean insert(K key, V value) {
if (isFull())
return false;
if (list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].addLast(new DictionaryNode<K,V>(key,value));
currentSize++;
modCounter++;
return true;
}
#Override
public boolean remove(K key) {
if (isEmpty())
return false;
if (!list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].remove(new DictionaryNode<K,V>(key,null));
currentSize--;
modCounter++;
return true;
}
public V getValue(K key) {
DictionaryNode<K,V> tmp = list[getHashCode(key)].find(new DictionaryNode<K,V>(key,null));
if (tmp == null)
return null;
return tmp.value;
}
#Override
public K getKey(V value) {
DictionaryNode<K,V> tmp = list[getHashCode(value)].find(new DictionaryNode<K,V>(null,value));
if (tmp == null)
return null;
return tmp.key;
}
public int size() {
return currentSize;
}
#Override
public boolean isFull() {
return currentSize == maxSize;
}
public boolean isEmpty() {
return currentSize == 0;
}
#Override
public void clear() {
currentSize = 0;
modCounter++;
for (int i=0; i<tableSize; i++)
list[i].makeEmpty();
}
public Iterator<K> keys() {
return new KeyIteratorHelper();
}
public Iterator<V> values() {
return new ValueIteratorHelper();
}
abstract class IteratorHelper<E> implements Iterator<E> {
protected DictionaryNode<K,V> [] nodes;
protected int idx;
protected long modCheck;
public IteratorHelper() {
nodes = new DictionaryNode[currentSize];
idx = 0;
int j = 0;
for (int i=0; i < tableSize; i++)
for (DictionaryNode n : list[i])
nodes[j++] = n;
nodes = (DictionaryNode<K,V>[]) ObjectSorter.quickSort(nodes);
}
public boolean hasNext() {
if (modCheck != modCounter)
throw new ConcurrentModificationException();
return idx < currentSize;
}
public abstract E next();
public void remove() {
throw new UnsupportedOperationException();
}
}
class KeyIteratorHelper<K> extends IteratorHelper<K> {
public KeyIteratorHelper() {
super();
}
public K next() {
return (K) nodes[idx++].key;
}
}
class ValueIteratorHelper<V> extends IteratorHelper<V> {
public ValueIteratorHelper() {
super();
}
public V next() {
return (V) nodes[idx++].value;
}
}
}

Java LinkedList with Object

Trying to implement a LinkedList that simulates a Portfolio, consisting of Stock objects. I'm struggling to figure out how to properly iterate through the list and check if each stock contains certain parameters. the SHAREPRICE method is the one I'm having trouble with specifically, if someone could help with that, I'd be very grateful. What I have so far:
import java.util.*;
public class Portfolio<AnyType> implements Iterable<AnyType> {
public int balance, shares;
private Stock<AnyType> beginMarker, endMarker, temp;
LinkedList<Stock> Portfolio = new LinkedList<Stock>();
java.util.Iterator<Stock> iter = Portfolio.iterator();
public int CASHIN(int x) {
balance = x;
return balance;
}
public int CASHOUT(int y) {
balance = balance + (-y);
return balance;
}
public int CASHBALANCE() {
return balance;
}
public void BUY(String t, int s, float pp) {
temp = new Stock<AnyType>(t, s, pp, pp, 0, null, null);
Portfolio.add(temp);
shares = shares + s;
}
public void SELL(String t, int s, float pp) {
shares = shares - s;
}
public void SHAREPRICE(String t, float pp)
{
if(Portfolio.contains(Stock.)
{
}
}
public void QUERY(String t) {
}
public int COUNTPORTFOLIO() {
return shares;
}
public void PRINTPORTFOLIO() {
}
public java.util.Iterator<AnyType> iterator() {
return new Iterator();
}
private class Iterator implements java.util.Iterator<AnyType> {
private Stock<AnyType> current = beginMarker.next;
private boolean okToRemove = false;
public boolean hasNext() {
return current != endMarker;
}
public AnyType next() {
if (!hasNext())
throw new java.util.NoSuchElementException();
AnyType nextItem = (AnyType) current.getTicker();
current = current.next;
okToRemove = true;
return nextItem;
}
public void remove() {
if (!okToRemove)
throw new IllegalStateException();
Portfolio.this.remove(current.prev);
okToRemove = false;
}
}
private class Stock<AnyType> implements Comparable<Stock<AnyType>> {
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public float getPurchasePrice() {
return purchasePrice;
}
public void setPurchasePrice(float purchasePrice) {
this.purchasePrice = purchasePrice;
}
public float getLatestPrice() {
return latestPrice;
}
public void setLatestPrice(float latestPrice) {
this.latestPrice = latestPrice;
}
public float getPctChange() {
return pctChange;
}
String ticker;
int sharesOwned;
float purchasePrice, latestPrice;
float pctChange = (latestPrice - purchasePrice) / purchasePrice;
Stock<AnyType> prev, next;
public Stock(String ticker, int sharesOwned, float purchasePrice,
float latestPrice, float pctChange, Stock<AnyType> prev,
Stock<AnyType> next) {
this.ticker = ticker;
this.sharesOwned = sharesOwned;
this.purchasePrice = purchasePrice;
this.latestPrice = latestPrice;
this.pctChange = pctChange;
this.prev = prev;
this.next = next;
}
public int compareTo(Stock<AnyType> pctChange) {
return ((Comparable) this.pctChange)
.compareTo(Stock.getPctChange());
}
}
}
class TestPortfolio {
public static void main(String[] args) {
}
}
Forward Direction:
while(itr.hasNext())
{
System.out.println(itr.next());
}
Reverse Direction
while(itr.hasPrevious())
System.out.println(itr.previous());
}

Categories