What is the difference between these two ways of dealing with stacks and queues? What are the both called?
First way:
import java.util.Arrays;
public class StackMethods {
private int top;
int size;
int[] stack ;
public StackMethods(int arraySize){
size=arraySize;
stack= new int[size];
top=-1;
}
public void push(int value){
if(top==size-1){
System.out.println("Stack is full, can't push a value");
}
else{
top=top+1;
stack[top]=value;
}
}
public void pop(){
if(!isEmpty())
top=top-1;
else{
System.out.println("Can't pop...stack is empty");
}
}
public boolean isEmpty(){
return top==-1;
}
public void display(){
for(int i=0;i<=top;i++){
System.out.print(stack[i]+ " ");
}
System.out.println();
}
}
Second way:
public class StackReviseDemo {
public static void main(String[] args) {
StackMethods newStack = new StackMethods(5);
newStack.push(10);
newStack.push(1);
newStack.push(50);
newStack.push(20);
newStack.push(90);
newStack.display();
newStack.pop();
newStack.pop();
newStack.pop();
newStack.pop();
newStack.display();
}
}
Also are they correct? trying to learn these well, but explanations across the internet are vague about these..
I'm not 100% sure what you mean with two ways.
Looking at your first code snippet, we can see that you are declaring the class StackMethods. In the second one you are instantiating an object of the class StackMethods.
So all you do in the main-method of your second code snippet is to create an object which is calling the methods push(), pop() and display() you declared in the class above. You didn't actually implement two datastructures, but just a basic stack.
The good news is, over all you have grasped the concepts of stacks, since your implementation of the class 'StackMethods' is correct overall.
In regards to what the difference between a Queue and a Stack is, this question might help you:
In case this didn't answer your question and I simply misunderstood it, please just comment and let me know so I can try to help you out a little better.
Related
My task is to transform a given class into an abstract and generic class ,producing a sequence of values of generic type ,and supporting a single constructor that accepts an initial value .
Here is the given class:
public class Progression {
protected long current;
public Progression(){
this.current=0;
}
public Progression(long start){
this.current=start;
}
public long nextValue(){
long answer= current;
advance();
return answer;
}
protected void advance(){
current++;
}
public void printProgression(int n){
System.out.println(nextValue());
for(int j=0;j<n;j++){
System.out.println(" "+nextValue());
}
System.out.println();
}
}
I made transform like this:
abstract class ReProgression<T> {
protected T current;
public ReProgression(T start){
current=start;
}
public T nextValue(){
T answer= current;
advance();
return answer;
}
public void advance(){
}
public void printProgression(int n){
System.out.println(nextValue());
for(int j=0;j<n;j++){
System.out.println(" "+nextValue());
}
System.out.println();
}
}
How can I increment the generic value "current" in advance() function?
Possible solution 1
Progression is a term that needs to be defined.
In your initial example of Progression, you are advancing a long, therfore its easy to determine how to advance. Just increment the number.
When you convert this to a generic type from a long, you no longer have any idea what the type is (hence, generic) so you have to somehow define how to advance. The generic type T has to define the bavious when it 'advances'. The standard way of doing this in Java is to use an interface
I would create something like this -
public interface Advancable{
public void advance();
}
In your ReProgression class, you would then use this interface like so -
abstract class ReProgression<T extends Advancable> {
protected T current;
public ReProgression(T start){
current=start;
}
public T nextValue(){
T answer= current;
advance();
return answer;
}
public void advance(){
current.advance();
}
public void printProgression(int n){
System.out.println(nextValue());
for(int j=0;j<n;j++){
System.out.println(" "+nextValue());
}
System.out.println();
}
}
And this is the solution. I should however discuss how the code is called.
In the initial example Progression, you would call it like this for example -
Progression p = new Progression(1);
p.printProgression(5);
Which would produce the output
1
2
3
4
5
To do the same with ReProgression, you would invoke it like this perhaps -
MyAdvancable<Long> startValue = new MyAdvancable<Long>(5);
ReProgression rp = new ReProgression(startValue);
rp.printProgression(5);
But you will also need to define MyAdvancable
Possible solution 2
You almost have the correct answer yourself. You problem is to "transform a given class into an abstract and generic class". Declaring a class abstract only makes sense if there is at least one abstract method. Ususally this is because the behaviour is not known or defined at the time of writing the code. This sounds very much like the unknown 'advancing' mechanism being commented on in your question. So what you have is almost what your solution is. Just remove the body of the advance() method -
abstract class ReProgression<T> {
protected T current;
public ReProgression(T start){
current=start;
}
public T nextValue(){
T answer= current;
advance();
return answer;
}
abstract void advance();
public void printProgression(int n){
System.out.println(nextValue());
for(int j=0;j<n;j++){
System.out.println(" "+nextValue());
}
System.out.println();
}
}
The reason I have two solutions is because from your question, and without more background on what topics are being covered in the current chapter of your book, to me either of the two are possible, and you will need to decide which of these, if any, might be your solution. Good luck with your journey learning Java!
I've been working on my college assignment about stacks in java, but I can't seem to find the help for this assignment. It's about switchbox routing and I'm required to use stack for this assignment. The assignment is due tomorrow, but there's no need to rush for answers since I'm only looking for the solutions and not the grades. Since the problem isn't written in english, I'm going to give short explanation.
The switchbox contains 4n pins, with n pins on each side of the box. The switchbox is routable only when none of the lines connecting a pair of pins intersect another. The input will be pairs of connected pin numbers.
A few possible solutions I've found but can't understand:
1. The problem can be solved with a similar algorithm as the one for the parentheses matching
2. Putting the pin numbers in stack and an array and compare them (this is the most confusing one)
My code so far (trying the second algorithm):
import java.util.Scanner;
import java.util.Stack;
public class Tester {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int cases=sc.nextInt();
for(int i=0;i<cases;i++){
int pin=sc.nextInt();
SwitchBox box=new SwitchBox(pin);
for(int j=0;j<pin*4;j++){
box.add(sc.nextInt());
}
boolean res=box.isRoutable();
if(res){
System.out.println("routable");
}
else{
System.out.println("not routable");
}
}
}
static class SwitchBox{
Stack<Integer> pins;
int[] pairs;
int[] comparator;
public SwitchBox(int pin){
this.pins=new Stack<Integer>();
this.pairs=new int[(pin*4)];
this.comparator=new int[this.pairs.length];
}
public boolean isRoutable(){
Stack<Integer> s=new Stack<Integer>();
for(int i=0;i<pairs.length;i++){
pairs[i]=pins.peek();
s.push(pins.pop());
}
for(int i=pairs.length-1;i>=0;i--){
if(pairs[i]!=s.pop()){
return true;
}
}
return false;
}
public void add(int pinNum){
if(pins.isEmpty()){
pins.push(pinNum);
}
else{
Stack<Integer> temp=new Stack<Integer>();
int top=(int)pins.peek();
while(top>pinNum){
temp.push(pins.pop());
if(pins.isEmpty()) top=pinNum;
else top=(int)pins.peek();
}
pins.push(pinNum);
while(!temp.isEmpty()){
pins.push(temp.pop());
}
}
}
}
}
In your add method else block is wrong. I was unable to understand what you try to do but you need to do next thing
public void add(int pinNum) {
if (pins.isEmpty()) {
pins.push(pinNum);
} else {
Integer last = pins.peek();
if (last == pinNum) {
pins.pop();
} else {
pins.push(pinNum);
}
}
}
After that isRoutable method just need to check pins stack. If it empty, then all fine. Else there are intersecting lines.
I am trying to solve this question from talent buddy.
http://www.talentbuddy.co/challenge/52a9121cc8a6c2dc91481f8d5233cc274af0110af382f40f
My code compiles and runs for small input, but is giving wrong ans for the following input-
http://tb-eval4.talentbuddy.co/5411559648d3e7eb5100024191810645628720530000.html
My Code is as follows -
import java.util.*;
class MyClass {
public void tweets_per_second(Integer[] tps, Integer k) {
PriorityQueue<Integer> pq =new PriorityQueue<Integer>(k, new Comparator<Integer>(){
public int compare(Integer i1, Integer i2){
if (i1.intValue()< i2.intValue()){
return 1;
}
else if(i1.intValue() ==i2.intValue()){
return 0;
}
else {
return -1;
}
}
});
for(int i=0;i<tps.length;i++){
if (pq.size()<=k){
pq.add(tps[i]);
System.out.println(pq.peek());
}
else{
pq.remove(tps[i-k]);
pq.add(tps[i]);
System.out.println(pq.peek());
}
}
}
public static void main(String[] args) {
MyClass t = new MyClass();
Integer[] tps = {6,9,4,7,4,1};
t.tweets_per_second(tps, 3);
}
}
Can someone please let me know what am I doing wrong? Any help will be appreciated. Thanks.
The code is entirely correct. At the end of the page you can see the following:
Error: your code didn't finish in less than 2 seconds.
Which tells you all you need to know.
As to why your code is slow - while using PriorityQueue or any built in collections etc is overall a good idea, it is very much not so in this case. I don't want to make educated guesses about how it's implemented, but one of add, remove, peek is not O(1) and eats up your time.
This question already has answers here:
Closed 10 years ago.
I'm trying to create a Stack to take a string and add each of the strings characters to it, but I was told it would be far more efficient use a LinkedList. How would I use a LinkedList to create and manipulate a stack?
An example would be very appreciated!
Ok, the problem is that you're not using First at all. Try the following:
public class Example
{
private LinkedList aList = new LinkedList();
public void push(char c) {
aList.addFirst(c);
}
public Object pop() {
return aList.removeFirst();
}
public boolean empty() {
return aList.isEmpty();
}
public static void main(String[] args) {
Stack exmpStack = new Stack();
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
exmpStack.push(ranString.charAt(i));
}
while (!exmpStack.empty()) {
System.out.print(exmpStack.pop());
}
}
}
Because you never use First it's always null - so your loop never runs at all! Instead of using that at all, just use the build in isEmpty() function.
Edit: Of course, you don't really need those functions at all - the following will work fine:
public class Example
{
private LinkedList aList = new LinkedList();
public static void main(String[] args) {
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
aList.push(ranString.charAt(i));
}
while (!aList.isEmpty()) {
System.out.print(aList.pop());
}
}
}
Now this is still a bit unsafe - you can go one step further by using the following:
private LinkedList<Character> aList = new LinkedList<>();
That way it's a bit safer, and returns Characters instead of Objects - and Characters can be implicitly cast to char :)
Java's LinkedList is a doubly linked list, with efficient accessors to get, add, and remove elements both at the end and at the head of the list, so you can use those methods to emulate a stack.
A LinkedList provides more operations that that of a stack.
You use a stack for pushing and popping your characters of your string. However you can only retrieve the character in the order that opposite the way you insert your string. So are you sure if you want this behaviour.
A linkedlist allows you to add/retrieve your data either from head / tail.
LinkedList is indeed more efficient, as Stack comes with synchronized methods by virtue of its reliance on Vector. In single-threaded applications, using the latter means paying the synchronization price for no benefit. Even in multi-threaded applications, you may want more control over synchronization.
Here's a possible LinkedList based solution. Please note the use of composition instead of inheritance. This will give you a well behaved Stack that cannot be abused by using List-related methods.
class MyStack<T> {
private List<T> list = new LinkedList<T>();
public void push(T object) { list.add(0, object); }
public T pop(T object) {
if (isEmpty()) throw new NoSuchElementException();
return list.remove(0);
}
public boolean isEmpty() { return list.isEmpty(); }
}
Nonetheless, if your stack is meant only for string characters as your question suggests, you might want to emulate a stack directly on a dynamic character array. I will leave that as an exercise to the reader, or I may provide it in a future edit.
Here is the sample: Stack implementation. Hope it helps.
It is done with C# but you get the idea
public static void main(String[] args) {
Player Anfallare = new Player("A");
Player Forsvarare = new Player("F");
MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
(...)
}
Is what I have in main function, now I made a own function,
public static void MotVarandra(int a, int f){
if(f >= a){
Anfallare.armees-=1;
}else{
Forsvarare.armees-=1;
}
}
which should set the object's variable to -=1.. But this doesn't work because the function doesnt know that Anfallare and Forsvarare is an object..
What can i do in this case?
You need to define the Players as class fields, instead of inside the main method.
For a gentle introduction to Java, I suggest you to start reading here:
http://download.oracle.com/javase/tutorial/java/index.html
Also, there are great book suggestions here: https://stackoverflow.com/questions/75102/best-java-book-you-have-read-so-far . Some of those books are great to begin learning.
Example here:
public class Game {
private static Player Anfallare, Forsvarare; // <-- you define them here, so they are available to any method in the class
public static void main(String[] args) {
Anfallare = new Player("A"); // <-- it is already defined as a Player, so now you only need to instantiate it
Forsvarare = new Player("F");
MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
// ...
}
public static void MotVarandra(int a, int f){
if(f >= a){
Anfallare.armees-=1; // <-- it is already defined and instantiated
}else{
Forsvarare.armees-=1;
}
}
}
While Aleadam's solution is by far the best answer, another thing you could do to specifically resolve this issue is change the arguments of the function:
public static void MotVarandra(Player a, Player f){
if(f.getDice(1) >= a.getDice(1)){
f.armees-=1;
}else{
a.armees-=1;
}
}
Ultimately, your optimal solution just depends on what your program is doing. Chances are, this is just another way of looking at it.
As a side note, be sure to use descriptive naming techniques, a and f are somewhat hard coded, and only make sense if you use only those variable names for your Players. It's best to not potentially limit your code.