I am trying to create a program where when the stack is full(for example 5 values can be held), and you try to push another value on the stack it performs the DropOut method. Where is sets ex. stack at position 0 to position 1 etc.... all the way to position 3 == to position 4. From here I want to delete the top value on the stack ( in this example it is the value at position 4 (5th value) ) From here I would then be able to add my next value to the top of the stack.... but my code is not working as intended. I am a beginner and appreciate any input available. Thanks for you time.
package jsjf;
import jsjf.exceptions.*;
import java.util.Arrays;
import java.util.*;
public class ArrayStack1<T> implements StackADT<T>
{
private final static int DEFAULT_CAPACITY = 5;
private int top;
private T[] stack;
private int next;
public ArrayStack1()
{
this(DEFAULT_CAPACITY);
}
public ArrayStack1(int initialCapacity)
{
top = -1;
stack = (T[])(new Object[initialCapacity]);
}
public void push(T element)
{
if (top+1==DEFAULT_CAPACITY){
DropOut();
//top=top-1;
pop();
stack[top]=element;
}
top++;
stack[top] = element;
}
public void DropOut(){
for (int x=0; x<stack.length-1; x++){
// if(x==stack.length){
// stack[x]=null;
// }
stack[x]=stack[x+1];
}
}
public T pop() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
T result = stack[top];
stack[top] = null;
return result;
}
public T peek() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
return stack[top];
}
public boolean isEmpty()
{
return (top < 0);
}
public int size(){
return (top+1);
}
public String toString()
{
String result = "";
for (int scan=0; scan <= top; scan++)
result = result + stack[scan].toString() + "\n";
return result;
}
public static void main(String[] args) {
ArrayStack1<Integer> t1=new ArrayStack1<Integer>(5);
t1.push(5);
t1.push(3);
t1.push(6);
t1.push(5);
t1.push(3);//
t1.push(4);
}
}
On push you are stacking the element twice when you reach max capacity. An else should fix your issue:
public void push(T element)
{
if (top+1==DEFAULT_CAPACITY){
DropOut();
//top=top-1;
pop();
stack[top]=element;
} else {
top++;
stack[top] = element;
}
}
Related
Hi,
Update: Thanks for all your suggestion
assuming that, this exercise it's like a rebus,
I have a list of numbers made with the concept of Cons and Nil,
List l = new Cons(**3**, new Cons(**2**,new Cons(**1**, new
Cons(**4**, new Cons(**1**, new Nil())))));
and I want to count how many of them are immediately followed by a lower number, recursively.
For example
[5,0,5,3].count() == 2, [5,5,0].count() == 1
The count() method is made by me (it cannot have any parameters), the rest is default, and I can't make and other method or use already defined one's like add(),size()...
The "NEXT" must have the next value after the current elem but I can't get a solution.
Any solutions are welcome.
abstract class List {
public abstract boolean empty();
public abstract int first();
public abstract int count();
}
class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty(){
return false;
}
public int first(){
return elem;
}
#Override
public int count() {
if(elem>NEXT) {
return 1 + next.count();
}else {
return next.count();
}
}
```![enter image description here](https://i.stack.imgur.com/kWo0v.jpg)
The following code will create a recursive list with N elements with N value being defined by the size of the amount of elements found in the int array called elements in RecursiveList class. Call the startRecursion() method to create a recursive list with the defined elements and call count() to get the amount of elements in the array that are immediately followed by a lower number.
Main Class
This your application entry point:
public static void main(String[] args) {
int count = RecursiveList.startRecursion().count();
System.out.printf("List has %d recursive elements", count);
}
RecursiveList Class
abstract class RecursiveList {
protected static int index = -1;
protected static int[] elements = new int[]{ 5,2,1,4,3,2,6 };
public static RecursiveList startRecursion() {
return new Cons();
}
public abstract boolean empty();
public abstract int count();
public abstract Integer getElement();
public static int incIndex() {
return index += 1;
}
}
Cons Class
public class Cons extends RecursiveList {
private static int result;
private final Integer elem;
private final RecursiveList prev;
private final RecursiveList next;
private Cons(Cons parent) {
prev = parent;
elem = incIndex() < elements.length ? elements[index] : null;
System.out.printf("Creating new Cons with element %d(%d)%n", elem, index);
next = elem != null ? new Cons(this) : null;
}
Cons() {
this(null);
}
public boolean empty() {
return false;
}
#Override
public /*#Nullable*/ Integer getElement() {
return elem;
}
#Override
public int count() {
if (elem != null)
{
if (prev != null && elem < prev.getElement())
result += 1;
if (next != null) {
return next.count();
}
}
return result;
}
}
EDIT
Alright here is the answer you were actually looking for. This completely conforms to the limitations imposed on this exercise that you provided. The solution uses pure Java, neither the class nor any of it's method or field declarations were modified in any way and no such new elements were added. I've only added the implementation where the exercise said you should.
Main Class
public static void main(String[] args) {
List l = new Cons(3, new Cons(2,new Cons(1, new
Cons(4, new Cons(1, new Nil())))));
assert l.count() == 3;
l = new Cons(5, new Nil());
assert l.count() == 0;
l = new Cons(5, new Cons(5, new Cons(0, new Nil())));
assert l.count() == 1;
l = new Cons(5, new Cons(0, new Cons(5, new Cons(3, new Nil()))));
assert l.count() == 2;
System.out.println("All tests completed successfully!");
}
Cons Class
import java.util.NoSuchElementException;
public class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty()
{ return false; }
public int first()
{ return elem; }
public int count()
{
try {
if (first() > next.first()) {
return 1 + next.count();
}
else return next.count();
}
catch (NoSuchElementException e) {
return 0;
}
}
}
Nil Class
import java.util.NoSuchElementException;
public class Nil extends List {
public boolean empty()
{ return true; }
public int first()
{ throw new NoSuchElementException(); }
public int count()
{
throw new IllegalAccessError();
}
}
public int NEXT(){
if(next!=null)
return next.first()
else
throw new Exception("No next element")
}
I am currently working on a Stack project where I am creating a generic Stack class. I've been looking on stack overflow for this, but couldn't find it. I need help creating a pop method in my code.
Here is what I have so far:
public class Stack<E>
{
public static final int DEFAULT_CAPACITY = 10;
private E [] elementData;
private int size;
#SuppressWarnings("unchecked")
public Stack()
{
this.elementData = (E[]) new Object[DEFAULT_CAPACITY];
}
#SuppressWarnings("unchecked")
public Stack(int capacity)
{
if(capacity < 0)
{
throw new IllegalArgumentException("capacity " + capacity);
}
this.elementData = (E[]) new Object[capacity];
}
public boolean isEmpty()
{
if(size == 0)
{
return true;
}
else
{
return false;
}
}
/*
The push method should add its parameter to the top of the stack.
*/
public void push(E item)
{
ensureCapacity(size+1);
elementData[size] = item;
size++;
}
private void ensureCapacity(int capacity)
{
if(elementData.length < capacity)
{
int newCapacity = elementData.length * 2 + 1;
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
I need help right here. I need to have the pop method remove and return the element at the top of the stack. If no items
are present, it should throw an "EmptyStackException".
public E pop()
{
if(isEmpty())
{
throw EmptyStackException
}
else
{
}
}
}
I figured it out, I give the credit to #ScaryWombat. The code is:
public E pop()
{
if(isEmpty())
{
throw new EmptyStackException();
}
else
{
return elementData[--size];
}
}
public E pop()
{
E item;
if(isEmpty())
{
throw new EmptyStackException();
}
else
{
item = elementData[size];
size--;
}
return item;
}
You need to make your return variable equal to the top of your stack array and then decrement your stack array. Also, you need to initialize your stack by setting size=0.
I created my own linked list in java(code below) and I was trying to store DNA?RNA sequences from a text file in an array of a custom data type that contains the enum DNA/RNA, as well as a linked list containing the actual DNA sequence. I don't know if the characters are just not being inserted into the linked list or if there is a problem with my toString but the output only prints the position and enum type, not the sequence from the list. Code is below
My node class
public class Node<E> {
private Node<E> next;
protected E data;
Node(E data,Node<E> nextVal){
this.data=data;
next=nextVal;
}
Node(Node<E> nextVal){
next=nextVal;
}
Node<E> Next(){
return next;
}
Node<E>setNext(Node<E> nextVal){
return next=nextVal;
}
E data(){
return data;
}
E setData(E it){
return data=it;
}
}
My Linked List Class
public class MyLinkedList<E> implements List<E>{
private Node<E> head;
private Node<E> tail;
protected Node<E> curr;
private int size;
MyLinkedList(int size){
this();
}
MyLinkedList(){
curr=tail=head=new Node<E>(null);
size=0;
}
#Override
public void clear() {
head.setNext(null);
curr=tail=head=new Node<E>(null);
size=0;
}
#Override
public void insert(E item) {
curr.setNext(new Node<E>(item, curr.Next()));
if(tail==curr)
tail=curr.Next();
size++;
}
#Override
public void append(E item) {
tail=tail.setNext(new Node<E>(item, null));
size++;
}
#Override
public E remove() {
if(curr.Next() ==null)
return null;
E item=curr.Next().data();
if(tail==curr.Next())
tail=curr;
curr.setNext(curr.Next().Next());
size--;
return item;
}
#Override
public void moveToStart() {
curr =head;
}
#Override
public void moveToEnd() {
curr=tail;
}
#Override
public void prev() {
if(curr==head)
return;
Node<E> temp=head;
while (temp.Next()!=curr)
temp=temp.Next();
curr=temp;
}
#Override
public void next() {
if(curr!=tail)
curr=curr.Next();
}
#Override
public int length() {
return size;
}
#Override
public int currPos() {
Node<E>temp=head;
int i;
for(i=0;curr!=temp;i++)
temp.Next();
return i;
}
#Override
public void moveToPos(int pos) {
assert (pos>=0)&& (pos<=size):
"Position out of Range";
curr=head;
for(int i=0;i<pos;i++)
curr.Next();
}
#Override
public E getValue() {
if(curr.Next()==null)
return null;
return curr.Next().data();
}
#Override
public String toString() {
String result = "";
Node current = head;
while(current.Next() != null){
result += current.data();
if(current.Next() != null){
result += ", ";
}
current = current.Next();
}
return "" + result;
}
}
This is the SequenceArr class which handles the operations on the array mentioned above (not complete here but all that is used in this example)
public class SequenceArr {
private TypeSeq [] SeqArr;
private int size=0;
private int MAXSIZE;
public SequenceArr(int MAXSIZE){
this.MAXSIZE=MAXSIZE;
SeqArr =new TypeSeq[MAXSIZE];
size=0;
}
public void insert(int pos, Type t, MyLinkedList<Character> seq){
TypeSeq currentEl=new TypeSeq(t,seq);
assert pos<=MAXSIZE: "Position over maximum size of array";
SeqArr[size]=currentEl;
size++;
}
public void remove(int pos){
if(SeqArr[pos]!=null){
while(SeqArr[pos+1]!=null){
SeqArr[pos]=SeqArr[pos+1];
}
if(SeqArr[pos+1]==null){
SeqArr[pos]=null;
}
}
else
System.out.print("No sequence to remove at specified position");
}
public void print(){
int i=0;
while (SeqArr[i]!=null){
System.out.println(i+"\t"+SeqArr[i].getType()+"\t"+SeqArr[i].getBioSeq().toString());
i++;
}
}
public void print(int pos){
if(SeqArr[pos]==null)
System.out.print("No sequence to print at specified position");
else
System.out.println(SeqArr[pos].getType()+"\t"+SeqArr[pos].getBioSeq().toString());
}
The custom data type i created that the array is made of
public class TypeSeq {
private Type type;
private MyLinkedList<Character> BioSeq;
public TypeSeq(Type type, MyLinkedList<Character> BioSeq){
this.type=type;
this.BioSeq=BioSeq;
}
public MyLinkedList<Character> getBioSeq() {
return BioSeq;
}
public void setBioSeq(MyLinkedList<Character> bioSeq) {
BioSeq = bioSeq;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}
and my DNAList class which handles input and contains the main method
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class DNAList {
static SequenceArr seqar;
public static void main(String []args){
MyLinkedList<String> hey=new MyLinkedList<>();
hey.append("Hello");
int arraysize= Integer.parseInt(args[0]);
String filePath=args[1];
File file=new File(filePath);
seqar=new SequenceArr(arraysize);
exefromFile(file);
}
public static void exefromFile(File file){
Scanner sc;
try{
sc=new Scanner(file);
while(sc.hasNextLine()){
String cmd=sc.nextLine();
if(!cmd.equals(""))
execute(cmd);
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
public static void execute(String s){
s=s.trim();
String [] commands=s.split("\\s+");
switch (commands[0])
{
case "insert":
int pos=Integer.parseInt(commands[1]);
Type t=Type.fromString(commands[2]);
char [] charArr=commands[3].toCharArray();
MyLinkedList<Character> seq=new MyLinkedList<>(charArr.length);
char curChar;
for(int i=0;i<seq.length();i++){
curChar=charArr[i];
if(t==Type.DNA&&(curChar=='A'||curChar=='C'||curChar=='G'||curChar=='T'))
seq.append(charArr[i]);
else
System.out.print("Error occurred while inserting");
}
seqar.insert(pos,t,seq);
break;
case "remove":
pos=Integer.parseInt(commands[1]);
seqar.remove(pos);
break;
case "print":
if(commands.length>1&&commands[1]!=null){
pos=Integer.parseInt(commands[1]);
seqar.print(pos);
}
else
seqar.print();
break;
case "clip":
pos=Integer.parseInt(commands[1]);
int start =Integer.parseInt(commands[2]);
int end =Integer.parseInt(commands[3]);
seqar.clip(pos,start,end);
break;
case "copy":
int pos1=Integer.parseInt(commands[1]);
int pos2=Integer.parseInt(commands[2]);
seqar.copy(pos1,pos2);
break;
case "transcribe":
pos=Integer.parseInt(commands[1]);
seqar.transcribe(pos);
break;
}
}
}
The input .txt file will say something like
insert 0 DNA AATTCCGGAATTCCGG
print
but the output will just be
0 DNA
and the sequence will not be printed. Any ideas?
There are quite a lot of bugs in the code, to mention some:
MyLinkedList(int size){
this();
}
MyLinkedList(){
curr=tail=head=new Node<E>(null);
size=0;
}
this always initialises your list with size 0.
char [] charArr=commands[3].toCharArray();
MyLinkedList<Character> seq=new MyLinkedList<>
(charArr.length);
I don't get the point of initialising your list with the size of 4 every-time. Also note, it's not going to initialise with the given size as you are always overriding it with 0.
#Override
public void insert(E item) {
curr.setNext(new Node<E>(item, curr.Next()));
if(tail==curr)
tail=curr.Next();
size++;
}
You are not utilising the concept of head at all, your first insert is a special case and needs to handled wisely.
#Override
public String toString() {
String result = "";
Node current = head;
while(current.Next() != null){
result += current.data();
if(current.Next() != null){
result += ", ";
}
current = current.Next();
}
return "" + result;
}
head is always going to be null, when you print it's always going to result in first element being null. Moreover, when you find a node with it's next pointing to null, you should use its data. In your code, before returning the result you need to append the data from the last element too.
Hi I am currently working on a queue wait time simultaion, over the course of 12 hours that adds a random number of people per line every minute while removing three from the front every minute as well. After the twelve hours are over i will average the rate in which they entered and exited the line. I need to perform this 50 times to get a more accurate model simulation. I do not currently know how to properly implement this. If i could get some pointers on where to begin it would be most appreciated.
Linked List Class
public class LinkedListQueue<E>{
private Node<E> head;
private Node<E> tail;
private int size;
public LinkedListQueue() {
}
public void enqueue(E element) {
Node newNode = new Node(element, null);
if (size == 0) {
head = newNode;
} else {
tail.setNextNode(newNode);
}
tail = newNode;
size++;
}
public E dequeue() {
if (head != null) {
E element = head.getElement();
head = head.getNextNode();
size--;
if (size == 0) {
tail = null;
}
return element;
}
return null;
}
public E first() {
if (head != null) {
return head.getElement();
}
return null;
}
public int getSize() {
return size;
}
public void print() {
if (head != null) {
Node currentNode = head;
do {
System.out.println(currentNode.toString());
currentNode = currentNode.getNextNode();
} while (currentNode != null);
}
System.out.println();
}
}
Node Class
public class Node<E>{
private E element;
private Node<E> next;
public Node(E element, Node next) {
this.element = element;
this.next = next;
}
public void setNextNode(Node next) {
this.next = next;
}
public Node<E> getNextNode() {
return next;
}
public E getElement() {
return element;
}
public String toString() {
return element.toString();
}
}
Simulation Class
import java.util.Random;
public class Simulation {
private int arrivalRate;
//you'll need other instance variables
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
}
public void runSimulation() {
//this is an example for using getRandomNumPeople
//you are going to remove this whole loop.
for (int i = 0; i < 10; i++) {
int numPeople = getRandomNumPeople(arrivalRate);
System.out.println("The number of people that arrived in minute " + i + " is: " + numPeople);
}
}
//Don't change this method.
private static int getRandomNumPeople(double avg) {
Random r = new Random();
double L = Math.exp(-avg);
int k = 0;
double p = 1.0;
do {
p = p * r.nextDouble();
k++;
} while (p > L);
return k - 1;
}
//Don't change the main method.
public static void main(String[] args) {
Simulation s = new Simulation(18, 10);
s.runSimulation();
}
}
It looks like you haven't started this assignment at all.
First, start with the main() method. A new Simulation object is created. Follow the constructor call to new Simulation(18, 10). For starters, you will see that the constructor is incomplete
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
// missing the handling of maxNumQueues
}
So, for starters, you probably want to define a new variable of type integer (since that is what is the type of maxNumQueues according to the Simulation constructor) in the Simulation class. From there, you obviously want to get back into the constructor and set your new variable to reference the constructor call.
Example:
public class Simulation {
private int arrivalRate;
private int maxNumQueues; // keep track of the maxNumQueues
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
this.maxNumQueues = maxNumQueues; // initialize our new local variable maxNumQueues
}}
I am using the following code to make an immutable queue.
import java.util.NoSuchElementException;
import java.util.Queue;
public class ImmutableQueue<E> {
//Two stacks are used. One is to add items to the queue(enqueue) and
//other is to remove them(dequeue)
private ImmutableQueue(ReversableStack<E> order, ReversableStack<E> reverse) {
this.order = order;
this.reverse = reverse;
}
//initially both stacks are empty
public ImmutableQueue() {
this.order = ReversableStack.emptyStack();
this.reverse = ReversableStack.emptyStack();
}
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
public ImmutableQueue<E> dequeue() {
if (this.isEmpty())
throw new NoSuchElementException();
if (!this.reverse.isEmpty()) {
return new ImmutableQueue<E>(this.order, this.reverse.tail);
} else {
return new ImmutableQueue<E>(ReversableStack.emptyStack(),
this.order.getReverseStack().tail);
}
}
private static class ReversableStack<E> {
private E head; //top of original stack
private ReversableStack<E> tail; //top of reversed stack
private int size;
//initializing stack parameters
private ReversableStack(E obj, ReversableStack<E> tail) {
this.head = obj;
this.tail = tail;
this.size = tail.size + 1;
}
//returns a new empty stack
public static ReversableStack emptyStack() {
return new ReversableStack();
}
private ReversableStack() {
this.head = null;
this.tail = null;
this.size = 0;
}
//Reverses the original stack
public ReversableStack<E> getReverseStack() {
ReversableStack<E> stack = new ReversableStack<E>();
ReversableStack<E> tail = this;
while (!tail.isEmpty()) {
stack = stack.push(tail.head);
tail = tail.tail;
}
return stack;
}
public boolean isEmpty() {
return this.size == 0;
}
public ReversableStack<E> push(E obj) {
return new ReversableStack<E>(obj, this);
}
}
private ReversableStack<E> order;
private ReversableStack<E> reverse;
private void normaliseQueue() {
this.reverse = this.order.getReverseStack();
this.order = ReversableStack.emptyStack();
}
public E peek() {
if (this.isEmpty())
throw new NoSuchElementException();
if (this.reverse.isEmpty())
normaliseQueue();
return this.reverse.head;
}
public boolean isEmpty() {
return size() == 0;
}
//returns the number of items currently in the queue
public int size() {
return this.order.size + this.reverse.size;
}
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue.enqueue(5);
newQueue.enqueue(10);
newQueue.enqueue(15);
int x = newQueue.size();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
}
But whenever I try to do a dequeue, I get a NoSuchElementException. Also, the newQueue.size function also returns 0.
What am I doing wrong ?
Thanks
You are missing the new ImmutableQueue reference..
since enqueue() method returns a new instance of ImmutableQueue
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
But on your main method you are discarding that object
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue.enqueue(5);
newQueue.enqueue(10);
newQueue.enqueue(15);
int x = newQueue.size();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
change your call to:
newQueue = newQueue.enqueue(5);
int x = newQueue.size();
System.out.println(x);
and you will see the size will change