I want to create a fixed-size stack and truncate the stack when is full. For this already exists a approach in Creating a fixed-size Stack, but I do not want to implement a class.
It is possible to do something like this?
Stack<String> stack = new Stack<String>(){
private static final long serialVersionUID = 1L;
public String push(String item) {
if (this.size() == FIXED_SIZE) {
//truncate()
}
return super.push(item);
}
};
And the rest of the stack methods remain the same?
So this is what I found in the documentation. I did not use or tested it. So I am not sure how this would work out. Because removeElementAt() is inherited from Vector class, and I am hoping that removeElementAt(0), will still remove the element at the bottom.
Stack<String> stack = new Stack<String>(){
private static final long serialVersionUID = 1L;
public String push(String item) {
if (this.size() == FIXED_SIZE) {
this.removeElementAt(0);
}
return super.push(item);
}
};
And also I am assuming that, what you meant by truncate is to remove the first-in element currently in the list, if you just want to reject the new coming element, you can just return null.
How about something like this:
Public class TruncatedStack<T> extends FixedStack<T>
{
private static final long serialVersionUID = 1L;
#Override
public String push(String item) {
if (this.top == size) {
this.top = -1;
return super.push(item);
}
}
Wrote this off the top of my head (untested). As mentioned in the comments, a fixed size stack is simply an array with a counter to keep track of the top.
public class FixedSizeStack {
int top, numElements;
int[] baseArray;
public FixedSizeStack(int maxSize) {
top = 0;
numElements = 0;
baseArray = new int[maxSize];
}
public void push(int num) {
baseArray[top] = num;
top = (top+1) % baseArray.length;
numElements++;
}
public int pop(int num) {
if(numElements == 0) return null; //or throw exception--you've removed too many elements!
numElements--;
top = (top == 0) ? (baseArray.length - 1) : (top - 1);
return baseArray[top];
}
}
Yep, you are almost exactly right. You just need to do a this.remove(0) and then you're done.
Stack<String> stack = new Stack<String>(){
#Override
public String push(String item) {
if (this.size() == FIXED_SIZE) {
this.remove(0)
}
return super.push(item);
}
};
Related
I'm trying to write an isEmpty() and an isFull() method that checks to see if a stack is empty or if it has values in it. I'm not sure how to write the methods so that all tests return as successes. Here is the code for the class and methods:
public class stack {
private int top;
private int maxSize;
private String stackItems[];
//default no-args constructor
public stack() {
this.maxSize = 5;
this.top = -1;
this.stackItems = new String[maxSize];
}
//allows you to set the max size of the stack
public stack(int maxSize) {
this.maxSize = maxSize;
this.top = -1;
this.stackItems = new String[maxSize];
}
//I have two tests for this method: testIsFullFalse and testIsFullTrue
public boolean isFull() {
return top == maxSize -1;
}
//Two tests for this method: testIsEmptyFalse and testIsEmptyTrue
public boolean isEmpty() {
// In progress
return top != maxSize -1;
}
Here are the tests:
#Test
void testIsEmptyTrue() {
// ARRANGE
stack myStack = new stack(1);
boolean actual, expected;
// ACT
actual = myStack.isEmpty();
expected = true;
// ASSERT
assertEquals(expected, actual);
}
#Test
void testIsEmptyFalse() throws StackFullException {
// ARRANGE
stack myStack = new stack(1);
String item = "Java is Fun!";
boolean actual, expected;
// ACT
myStack.push(item);
actual = myStack.isEmpty();
expected = false;
// ASSERT
assertEquals(expected, actual);
}
#Test
void testIsFullTrue() throws StackFullException {
// ARRANGE
stack myStack = new stack(1);
String item = "testing";
boolean actual, expected;
// ACT
myStack.push(item);
actual = myStack.isFull();
expected = true;
// ASSERT
assertEquals(expected, actual);
}
#Test
void testIsFullFalse() throws StackFullException {
// ARRANGE
stack myStack = new stack(1);
boolean actual, expected;
// ACT
actual = myStack.isFull();
expected = false;
// ASSERT
assertEquals(expected, actual);
}
Right now, testIsEmptyTrue() and testIsFullFalse() come back as successes, and testIsEmptyFalse() and testIsFullTrue() come back as failures. I want them all to come back as successes. Any pointers on how to fix the methods?
A little hard without seeing the push method, but the problem might be here:
//Two tests for this method: testIsEmptyFalse and testIsEmptyTrue
public boolean isEmpty() {
// In progress
return top != maxSize -1;
}
The isEmpty() method will always return true unless top does equal maxSize -1.
For a method called "isEmpty", how about something like this:
private static final int bottom = -1;
private int top = bottom;
private int maxSize;
private String stackItems[];
//default no-args constructor
public stack() {
this.maxSize = 5;
//this.top = -1;
this.stackItems = new String[maxSize];
}
//allows you to set the max size of the stack
public stack(int maxSize) {
this.maxSize = maxSize;
//this.top = -1;
this.stackItems = new String[maxSize];
}
...
//Two tests for this method: testIsEmptyFalse and testIsEmptyTrue
public boolean isEmpty() {
// In progress
return top == bottom;
}
I'm trying to implement a generic stack.
Here's the interface
package stack;
public interface Stack<T>{
void push(T number);
T pop();
T peek();
boolean isEmpty();
boolean isFull();
}
Here's the class
package stack;
import java.lang.reflect.Array;
import java.util.EmptyStackException;
public class StackArray <T> implements Stack<T>{
private int maxSize;
private T[] array;
private int top;
public StackArray(int maxSize) {
this.maxSize = maxSize;
// #SuppressWarnings("unchecked")
this.array = (T[]) Array.newInstance(StackArray.class, maxSize);
this.top = -1;
}
private T[] resizeArray() {
/**
* create a new array double the size of the old, copy the old elements then return the new array */
int newSize = maxSize * 2;
T[] newArray = (T[]) Array.newInstance(StackArray.class, newSize);
for(int i = 0; i < maxSize; i++) {
newArray[i] = this.array[i];
}
return newArray;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize-1;
}
public void push(T element) {
if(!this.isFull()) {
++top;
array[top] = element;
}
else {
this.array = resizeArray();
array[++top] = element;
}
}
public T pop() {
if(!this.isEmpty())
return array[top--];
else {
throw new EmptyStackException();
}
}
public T peek() {
return array[top];
}
}
Here's the Main class
package stack;
public class Main {
public static void main(String[] args) {
String word = "Hello World!";
Stack <Character>stack = new StackArray<>(word.length());
// for(Character ch : word.toCharArray()) {
// stack.push(ch);
// }
for(int i = 0; i < word.length(); i++) {
stack.push(word.toCharArray()[i]);
}
String reversedWord = "";
while(!stack.isEmpty()) {
char ch = (char) stack.pop();
reversedWord += ch;
}
System.out.println(reversedWord);
}
}
The error is
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Character
at stack.StackArray.push(StackArray.java:40)
at stack.Main.main(Main.java:14)
line 40 is in the push method
array[top] = element;
Side Question:
Any way to suppress the warning in the constructor? :)
The underlying issue is type erasure. The relevant implications of this means that an instance of the Stack class doesn't know it's type arguments at run-time. This is the reason why you can't just use the most natural solution here, array = new T[maxSize].
You've tried to work around this by creating an array using Array.newInstance(...), but unfortunately this array does not have elements of type T either. In the code shown the elements are of type StackArray, which is probably not what you intended.
One common way of dealing with this is to use an array of Object internally to Stack, and cast any return values to type T in accessor methods.
class StackArray<T> implements Stack<T> {
private int maxSize;
private Object[] array;
private int top;
public StackArray(int maxSize) {
this.maxSize = maxSize;
this.array = new Object[maxSize];
this.top = -1;
}
// ... lines removed ...
public T pop() {
if(this.isEmpty())
throw new EmptyStackException();
return element(top--);
}
public T peek() {
if(this.isEmpty())
throw new EmptyStackException();
return element(top);
}
// Safe because push(T) is type checked.
#SuppressWarnings("unchecked")
private T element(int index) {
return (T)array[index];
}
}
Note also you have a bug in the resizeArray() method where maxSize is never assigned a new value. You don't really need to keep track of maxSize, as you could just use array.length.
I think there is also an issue with peek() when the stack is empty in the original code.
Your code creates arrays of StackArray, and then you try to stick Character objects in it, just as if you were doing this:
static void add(Object arr[], Object o) {
arr[0] = o;
}
public static void main(String[] args) {
StackArray stack[] = new StackArray[1];
Character c = 'x';
add(stack, c);
}
Is this code a stack?
How I can make it better?
This is my first one.
Can i do this using ArrayList?
public class Stack implements IADT {
private final int[] stackArray = new int[10];
private int top;
private int nr;
public Stack(){
top = -1;
}
#Override
public String pop() {
return Integer.toString(stackArray[top--]);
}
#Override
public String peek() {
return Integer.toString(stackArray[top]);
}
#Override
public void push(String value) {
//...
}
I didn't added the isEmpty() method.
Yes, it is.
But you can add checking for overflow, underflow.
And this will be better if you'll try using collections.
I have worked on this the whole day and cannot think of a good solution. I am to implement a breadth first search algorithm in order to solve a sliding puzzle. Here are the relevant parts of my code so far. (I have yet to test if it works since it is incomplete)
So far, this code is expected to traverse through all the possibilities and arrive at the goal. However, I cannot think of a way to record that path from initial to goal state.
private void addToQueue(PuzzleState nextPS) {
if (notVisitedAndNotNull(nextPS))
queue.add(nextPS);
}
private void solveByBFS() {
queue.clear();
queue.add(this.initialState);
long startTime = System.currentTimeMillis();
while(!queue.isEmpty()) { //TODO create a way to backtrack and get a path
if (queue.size() > maxQueueSize)
maxQueueSize = queue.size();
this.currentState = queue.poll();
if (this.currentState.equals(finalState)) { //TODO check if cannot progress any further and terminate
System.out.println("Successful! Ending Time: " + startTime);
return;
}
visited.add(this.currentState);
this.addToQueue(this.currentState.moveUp());
this.addToQueue(this.currentState.moveDown());
this.addToQueue(this.currentState.moveRight());
this.addToQueue(this.currentState.moveLeft());
}
return;
}
So I want a way to back track and get from the goal node to the initial state, reverse the path, and then print it out in a list.
Here is the data structure I am using:
public class SimplePuzzleState implements PuzzleState{
private int rowSz;
private int sz;
private int zeroPos;
private int[] gameState;
#Override
public void configureState(int[] gameState) {
rowSz = (int) Math.sqrt(gameState.length);
sz = gameState.length;
zeroPos = PuzzlePropertyUtility.findZeroPosition(gameState);
this.gameState = gameState;
}
#Override
public PuzzleState moveUp() {
if (zeroPos <= rowSz - 1) {
return null;
}
this.swap(zeroPos, zeroPos - rowSz);
return this.createNewUpdatedState();
}
#Override
public PuzzleState moveDown() {
if (zeroPos >= sz - rowSz) {
return null;
}
this.swap(zeroPos, zeroPos + rowSz);
return this.createNewUpdatedState();
}
#Override
public PuzzleState moveLeft() {
if (zeroPos % rowSz <= 0) {
return null;
}
this.swap(zeroPos, zeroPos - 1);
return this.createNewUpdatedState();
}
#Override
public PuzzleState moveRight() {
if (zeroPos % rowSz >= rowSz -1) {
return null;
}
this.swap(zeroPos, zeroPos + 1);
return this.createNewUpdatedState();
}
#Override
public boolean isEqual(PuzzleState other) {
if (other != null) {
if (this.getStateArray() instanceof int[] && other.getStateArray() instanceof int[])
return (Arrays.equals(this.getStateArray(), other.getStateArray()));
}
return false;
}
#Override
public int[] getStateArray() {
return gameState;
}
private void swap(int pos1, int pos2) {
int temp = this.gameState[pos1];
this.gameState[pos1] = this.gameState[pos2];
this.gameState[pos2] = temp;
}
private PuzzleState createNewUpdatedState() {
PuzzleState newState = new SimplePuzzleState();
newState.configureState(this.getStateArray());
return newState;
}
}
Here is the PuzzleState Interface:
public interface PuzzleState {
public void configureState(int[] gameState);
PuzzleState moveUp();
PuzzleState moveDown();
PuzzleState moveLeft();
PuzzleState moveRight();
boolean isEqual(PuzzleState other);
int[] getStateArray();
}
I have thought about adding an attribute to SimplePuzzleState to include a parent node.
However, I cannot modify the interface which it implements since my instructor does not allow that. Therefore, I cannot backtrack using a linked list method. Are there any smart ways to record the correct path? In the end, my instructor wants me to print a list containing enums which represent the movements. So I have to figure how to map the enums to functions moveUp, moveDown etc.
Thank you in advance. I apologize for posting so much code, but I really need advice on which direction I should take.
You have the right idea. If you can't add parent pointers to the states, then just maintain a HashMap with the same information called something like previous. When you create the four
child states, add mappings from the parent to these four.
// A map to hold parent relations.
HashMap<SimplePuzzleState, SimplePuzzleState> previous = new HashMap<>();
...
// Now change the add function.
private void addToQueue(PuzzleState parentPS, PuzzleState nextPS) {
if (notVisitedAndNotNull(nextPS)) {
queue.add(nextPS);
previous.add(nextPS, parentPS);
nextPS.updateParent(this); // and update where we got from
}
}
// Then update the calls to match:
this.addToQueue(currentState, this.currentState.moveUp());
...
When you find the goal, trace back to the start using the hash just as you would the parent pointers.
if (this.currentState.equals(finalState)) {
System.out.println("Successful! Ending Time: " + startTime);
System.out.println("Path back to start:");
PuzzleState state = currentState;
do {
state.print();
state = previous.get(state);
} while (state != null);
}
Add to SimplePuzzleState another field called gotHereFrom and when you call addToQueue() update this field (per each item). When you're done, instead if printing "successful" and return; start iterating back according to gotHereFrom and print the nodes all the way back:
public class SimplePuzzleState implements PuzzleState{
private int rowSz;
private int sz;
private int zeroPos;
private int[] gameState;
private SimplePuzzleState gotHereFrom; // add this guy
...
protected void updateParent(SimplePuzzleState gotHereFrom) {
this.gotHereFrom = gotHereFrom;
}
...
}
and:
private void addToQueue(PuzzleState nextPS) {
if (notVisitedAndNotNull(nextPS)) {
queue.add(nextPS);
nextPS.updateParent(this); // and update where we got from
}
}
iterating the results:
...
if (this.currentState.equals(finalState)) { //TODO check if cannot progress any further and terminate
System.out.println("Successful! Ending Time: " + startTime);
String path = "";
while (gotHereFrom != null) {
path += " -> " + gotHereFrom;
gotHereFrom = gotHereFrom.getGotHereFrom();
}
System.out.println(path);
return;
}
I am trying to write program and keep getting a nullPointerException when I call a particular method, what does this mean ?
I think it should be
private int size; //non static
private static <S extends Comparable<S>> MyList<S> leftHalf(MyList<S> list) {
MyList<S> leftSide = new MyList<S>();
int middle = list.size() /2;
for (int countToMiddle = 0; countToMiddle < middle; countToMiddle++) {
leftSide.addEnd(list.head());
}
return leftSide;
}
if no, please provide more information about what this method should do.
upd:
construction issue
public MyList() { //takes no arguments
nodes = null;
}
public MyList(T... args) { //takes any number of arguments
this();
for(T t : args){
add(t);
}
}
upd:
addEnd issue
public void addEnd(T item) {
if (nodes == null) {
nodes = new NodesList<T>(item, null);
return;
}
if (nodes.tail == null) {
nodes.tail = new NodesList<T>(item, null);
} else {
nodes.tail == new NodesList<T>(nodes.tail, item);
}
}