sorry, just following on from the question I had here : here I am trying to run this method to remove a generic value (EltType) from a double sided queue(deque), but I keep getting an error in that, I call insertFirst twice, and insert the value "3" into the array twice, then, when I run removeFirst, it will print out "3" once, and then "Null" thereafter. Would anyone be able to help me out please ?
class ArrayBasedDeque<EltType> {
private final int CAPACITY = 10;
private int capacity;
private int end;
private EltType deque[];
public ArrayBasedDeque() {
this.capacity = CAPACITY;
deque = (EltType[]) (new Object[capacity]);
}
public EltType removeFirst() {
EltType[] tempArray;
EltType returned = deque[0];
tempArray = (EltType[]) new Object[capacity];
for (int i=1;i<capacity;i++) {
tempArray[i-1] = deque[i];
}
deque = tempArray;
return returned;
}
public boolean isEmpty() {
return end == 0;
}
public void insertFirst(EltType first) {
if(!isEmpty()) {
EltType[] tempArray;
tempArray = (EltType[]) new Object[capacity+1];
for (int i=0;i<deque.length;i++) {
tempArray[i+1] = deque[i];
}
deque = tempArray;
}
deque[0] = first;
}
}
Thank you :)
The big glaring issue is that end never changes. isEmpty() will always return true. Now let's look at your insertFirst() method.
public void insertFirst(EltType first) {
if(!isEmpty()) {
EltType[] tempArray;
tempArray = (EltType[]) new Object[capacity+1];
for (int i=0;i<deque.length;i++) {
tempArray[i+1] = deque[i];
}
deque = tempArray;
}
deque[0] = first;
}
Knowing that isEmpty() always returns true no matter what, what is the problem with this piece of code?
You need to update your end pointer too when you remove an element.
You should also investigate System.arrayCopy()
Related
Hello I was trying to figure out how to reverse a queue with the use of an array. Ive attached the queue class and a the runner class which created the queue and adds the elements inside of it. The reverse method I have creates an array and my thought would be to check the elements remove and add it to the array created. Im new to queue and an a little lost. Thanks for any help an advanced.
public class Queue{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
} else
System.out.println(
"Trying to enqueue into a full queue");
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println(
"Trying to dequeue from an empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println(
"Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
}
// queue created with reverse method
public class RunnerQueue {
public static void main(String args[]){
Queue q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
public static void reverseQueue(Queue Q){
int[] revQue = new int(Q.size);
While(!Q.isEmpty()){
}
}
}
I think you have the right idea so far. Assuming all of your queue methods work, such as size, enqueue, dequeue, etc., then all you have do is as you dequeue elements off of the queue one by one, insert those elements from the end of the array towards the start. You can have a counter that keeps track of where you want to insert the element in the array. This counter would start at Q.size() - 1 since queues follow the FIFO, first-in-first-out principle. Then, with the help of a helper method, you can set the items variable in your queue to revQue after you've populated the elements of the array with the items of the original queue in reverse order. For example, you could modify your reverseQueue method to look something like this,
public static void reverseQueue(Queue Q){
int[] revQue = new int[Q.size()];
int i = Q.size() - 1;
while(!Q.isEmpty()){
revQue[i] = Q.dequeue();
i--;
}
Q.setItems(revQue);
}
And this is what the setItems method would look like, added to your Queue class,
public void setItems(Object[] items) {
this.items = items;
this.QUEUE_SIZE = items.length;
this.front = 0;
this.back = items.length - 1;
this.count = items.length;
}
Just a note that the setItems method here assumes perfect circumstances, meaning that the items parameter passed in has a valid element at each spot within the array. For the reverseQueue method, this should work assuming that your other queue methods work as intended. But keep in mind that the setItems method can cause problems if you pass in an array with gaps in it; for example, null elements at certain indices.
Here's the update class:
public class Queue
{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
} else
System.out.println(
"Trying to enqueue into a full queue");
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println(
"Trying to dequeue from an empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println(
"Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
public static void reverseQueue(Queue q)
{
if(q.isEmpty())
{
return;
}
Object data = q.peek();
q.dequeue();
reverseQueue(q);
q.enqueue(data);
}
public static void printQueue(Queue q)
{
while(!q.isEmpty())
{
System.out.println(q.dequeue());
}
}
public static void main(String[] args)
{
Queue q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
reverseQueue(q);
printQueue(q);
}
}
So the idea is pop the element from the queue, if it has elements. Call the reverseQueue method for the remaining values in the queue, then put the values that were removed from the queue back onto it. Making it in the reverse order.
I need to implement the size() function so that it will count the number of elements in a list.
I cannot use a count variable. Should work (given our 'top' node and the constructors [default] setup). I know i have to use a loop but i don't know how to reference indices like i do with arrays.
public class DropOutStack<T> implements StackADT<T> {
private int max;
private LinearNode<T> top;
public DropOutStack(){
max = 10;
top = null;
}
public DropOutStack(int capacity){
setMaxSize(capacity);
}
public DropOutStack(T element){
LinearNode<T> temp = newLinearNode(element);
temp.setNext(top);
top = temp;
max = 10;
}
public DropOutStack(T element, int capacity){
LinearNode<T> temp = newLinearNode(element);
temp.setNext(top);
top = temp;
setMaxSize(capacity);
}
public int size(){
}
public boolean isEmpty(){
if(top == null) return true;
return false;
}
}
DropOutStack list = new DropOutStack("T",4);
System.out.print(list.size());
Should print 1. Since only "T" has been added.
Adding a screenshot of the composition class. I think I have to use a method from there. Interface just declares the push pop peek isempty functions. No code. Not needed for the size() function I believe. This is my first programming class so I hope I gave everything needed to solve this. Please help enter image description here
Something like that will count the elements:
ToIntFunction<LinearNode<T>> counter = (node) -> {
int count = 0;
while( node != null ) {
count++;
node = node.getNext();
}
return( count );
};
…applied in the DropOutStack class size() function:
public int size() {
return( counter.applyAsInt( top ) );
}
I need help with a Circular Doubly Linked List in Java.
This is my code (originally coded by "sanfoundry"; it uses interfaces):
LinkedList.java:
public class LinkedList<T extends Comparable<T>> implements
ILinkedList<T> {
private ILinkedListNode<T> head;
private ILinkedListNode<T> end;
private int size;
public LinkedList() {
head = null;
end = null;
head = null;
size = 0;
}
#Override
public void append(T element) {
ILinkedListNode<T> tempNode = new LinkedListNode(element, null, null);
if (head == null) {
head = tempNode;
end = head;
} else {
tempNode.setPrev(end);
tempNode.setNext(tempNode);
end = tempNode;
}
size++;
}
// should return element at position "index"
#Override
public T get(int index) {
return null;
}
#Override
public int size() {
return size;
}
#Override
public ILinkedListNode<T> getHead() {
return head;
}
}
Now I need help to get it working. Did I do something wrong and what do I have to code in method "public T get (int index)"? Sorry, but I'm a Java noob :(
EDIT: Is this a possible solution?
public T get(int index) {
T element = null;
if (index == 0) {
element = head.getElement();
} else if (index == size()-1) {
element = head.getPrev().getElement(); // end.getElement() also possible
} else {
ILinkedListNode<T> temp = head;
for (int i = 0; i < index; i++) {
temp = temp.getNext();
}
element = temp.getElement();
}
return element;
}
You should traverse the LinkedList, keeping track of your current position as you go. When your current position is equal to the index passed in, then you can return the T from that node.
Read about traversing a linked list here.
Try making some test cases. Ideally you'll want to use a real test framework but using a normal main method could work. For example:
public static void main(String[] args) {
ILinkedList<String> a = new LinkedList<String>();
System.out.println(a.size()); // 0
System.out.println(a.getHead()); // null
a.append("foo");
System.out.println(a.size()); // 1
System.out.println(a.get(0)); // "foo"
System.out.println(a.get(1)); // decide yourself what this should result in
a.append("bar");
System.out.println(a.size()); // 2
System.out.println(a.get(0)); // "foo"
System.out.println(a.get(1)); // "bar"
a.append("baz");
System.out.println(a.size()); // 3
System.out.println(a.get(0)); // "foo"
System.out.println(a.get(1)); // "bar"
System.out.println(a.get(2)); // "baz"
}
Expand the test as necessary. See if the code returns what you expect it to, or if the code never returns, or throws an exception, etc.... The easiest way to check whether your code is running properly is, after all, to actually run it.
Hint: the code, as of this writing, has some errors.
Also, if the code can run as expected, consider:
Traversing the nodes backward if it's faster than forward.
Using a recursion instead of iteration.
So i am trying to make an array based generic heap that i can use with my tester class. Much of what i have is based of my understandings of trees and some research online as well as from my textbook; both which have very limited info on what i am looking for. However, i did manage to get all the methods in need and when i run it, i get this error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
at q1.Heaps.<init>(Heaps.java:23)
at q1.createGui.<init>(Gui.java:46)
at q1.Gui.main(Gui.java:18)
Im guessing it has to do with how i declare and initialize my Comparable array, which i am having trouble figuring out how to.
package q1;
import java.util.Arrays;
public class Heaps<E extends Comparable<E>> {
Comparable[] data;
int size;
/**
* Constructor with s as size
*/
#SuppressWarnings("unchecked")
public Heaps(int s) {
size = 0;
data = (E[]) new Object[s];
}
/**
* Adds a value to the heap
*/
public void add(E value) {
if (full()) // expand array
ensureCapacity(2*size);
size++;
data[size] = value;
if (size > 1)
heapifyUp();
}
/**
* Checks if the array is full
*/
private boolean full()
{
return (size == data.length-1);
}
private void heapifyUp()
{
Comparable<E> temp;
int next = size;
while (next != 1 && data[next].compareTo(data[next/2]) > 0)
{
temp = data[next];
data[next] = data[next/2];
data[next/2] = temp;
next = next/2;
}
}
private void heapifyDown()
{
Comparable<E> temp;
int next = 0;
while (next*2 <= size) // node has a child
{
int child = 2*next; // left child
if (child < size &&
data[child].compareTo(data[child+1]) > 0)//left smaller than right
child++; // right child instead
if (data[next].compareTo(data[child]) > 0)
{
temp = data[next];
data[next] = data[child];
data[child] = temp;
next = child;
}
else;
next = size; // stop loop
}//end while
}
/**
* Removes all occurrence of element
*/
public boolean removeAll(E element) {
if (contains(element) && !(isEmpty())){
for (int i = 0; i < size; i++){
if(element.equals(data[i])){
data[i] = data[size-1];
}
heapifyDown();
}
return true;
}
return false;
}
/**
* Removes 1st occurrence of element
*/
public boolean remove(E element) {
if (contains(element) && !(isEmpty())){
for (int i = 0; i < size; i++){
if(element.equals(data[i])){
data[i] = data[size-1];
heapifyDown();
return true;
}
}
}
return false;
}
public boolean isEmpty() {
return size == 0;
}
public Comparable<E>[] ensureCapacity(int s) {
return Arrays.copyOf(data, 2*s);
}
/**
* Converts the heap into its String representation.
* #return the String representation
*/
public Comparable<E>[] iteratorPreOrder()
{
Comparable<E>[] temp = (E[]) new Object[size];
temp[0] = data[0];
int i = 1;
int count = 1;
while(data[2*i] != null){
temp[count] = data[2*i];
++i;
++count;
}
i = 1;
while(data[(2*i) +1] != null){
temp[count] = data[(2*i) +1];
++i;
++count;
}
return temp;
}
public int countOccurance(E element){
int count = 0;
for (int i =0; i < size; i++){
if(element.equals(data[i])){
count++;
}
}
return count;
}
public boolean contains (E element)
{
for (int i=0; i<size; i++){
if (element.equals(data[i])){
return true;
}
}
return false;
}
}
If you could please show me how i would solve this problem, i would greatly appreciate it. Thanks
EDIT: SO i edited the my class and now it works when i do data = (E[]) new Comparable[s]. So why does java not allow generic Array types, what makes it different from Arraylist, Stacks, Queues, and/or LinkedList which can be generic?
You are creating an Object[] and then trying to cast it to a Comprable[]. The compiler was telling you what you did wrong with the unchecked cast error.
You want data to be E[] data and the line to be:
data = new E[s];
Note: this could run into issues with how Java handles generics.
Structure of my class:
public class Priorityy implement Comparable {
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
return 1;
} else if (this.key > p.key) {
return -1;
} else {
return 0;
}
}
}
Th problem is that p.key is always null, why exactly is that? I have my array initialized with elements in it but it always throws NullPointerException whenever I try Arrays.sort(arr).
How can I fix this?
Edit: Here is the complete code and print did print the elements of array arr:
import java.util.Arrays;
class Priorityy implements Comparable {
int size;
int front = 0;
int rear = 0;
static Priorityy[] arr = new Priorityy[3];
int key;
String value;
public Priorityy(int key, String value) {
this.key = key;
this.value = value;
insert();
}
public void insert() {
arr[front] = this;
System.out.println(arr[front].value);
while (front + 1 != 3) {
front = front + 1;
}
}
public Priorityy remove() {
Priorityy x = arr[front];
front = front - 1;
return x;
}
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
System.out.println(p.key);
return 1;
} else if (this.key > p.key) {
System.out.println("3");
return -1;
} else {
System.out.println("4");
return 0;
}
}
public static void main(String... s) {
new Priorityy(10, "Watch");
new Priorityy(40, "Laptop");
new Priorityy(60, "Wallet");
Arrays.sort(arr);
for (Priorityy element : arr) {
System.out.println(element.key);
System.out.println(element.value);
}
}
}
As per your code
Priorityy p = (Priorityy)pe;
^^ ---------- this is null
You have null object in the array. Handle null object gracefully.
For example
if(pe instanceof Priorityy){ // return false for null object
// your code goes here
}
Better use Generic Comparable and use Integer.compare(int,int) to compare two int values.
class Priorityy implements Comparable<Priorityy> {
public int compareTo(Priorityy pe) {
if (pe != null) {
return Integer.compare(this.key, pe.key);
} else {
// return what ever if pe is null
}
}
}
You're putting things into your array in a really strange manner.
But given that, the problem is that you're not using a static field to store the next position to insert an element into, so the next time you create an instance of Priorityy, the field first contains the value zero again. So you're inserting all three objects into element zero of the array.
Change one line of your code and it will work:
int front = 0;
To:
static int front = 0;
I don't see where you are using size and rear but you probably want these to be static too.
One other suggestion: Java has a nice short syntax for increasing or decreasing the value of a variable by one using the ++ or -- operator, so you can shorten things by saying:
front++;
instead of
front = front + 1;
(and front-- instead of front = front - 1)