Here is a question about Stack on StackOverflow.
My question might seem very very vague but if you check my program which I have written then you might understand what I am trying to ask.
I have implemented the stack myself. I present the user with 3 choices. Push, Pop and View the stack. When view(display) method is called then bunch of 0s show instead of nothing. We know the stack contains nothing unless we put something on it. But since my implemented stack is stack of integers using array, the display method when called shows bunch of 0s(the default values of integers in the array). How do I show nothing instead of 0s. I know I can add ASCII for whitespace character but I think it would still violate the rule of stack(Stack should be empty when there is not element, not even code for whitespace).
Here is my program:
import java.util.Scanner;
public class StackClass
{
public static void main(String []args)
{
Scanner input=new Scanner(System.in);
int choice=0;
int push;
Stack stack=new Stack();
do
{
System.out.println("Please select a stack operation:\n1. Press 1 for adding to stack\n2. Press 2 for removing elements from stack\n3. View the stack");
choice=input.nextInt();
switch(choice)
{
case 1:
System.out.println("Please enter the number that you want to store to stack");
push=input.nextInt();
stack.push(push);
case 2:
stack.pop();
case 3:
stack.display();
}
}
while((choice==1)||(choice==2)||(choice==3));
}
}
class Stack
{
private int size;
private int[] stackPlaces=new int[15];
private int stackIndex;
Stack()
{
this.size=0;
this.stackIndex=0;
}
public void push(int push)
{
if(size<15)
{
stackPlaces[stackIndex]=push;
size++;
stackIndex++;
}
else
{
System.out.println("The stack is already full. Pop some elements and then try again");
}
}
public void pop()
{
if(size==0)
{
System.out.println("The stack is already empty");
}
else
{
stackPlaces[stackIndex]=0;
size--;
stackIndex--;
}
}
public void display()
{
System.out.println("The stack contains:");
for(int i=0;i<stackPlaces.length-1;i++)
{
System.out.println(stackPlaces[i]);
}
}
}
In display(), simply change your loop to use size for the loop condition, so that you display the logical number of elements:
for (int i=0;i < size; i++)
{
System.out.println(stackPlaces[i]);
}
Note that your existing loop was only showing 14 of the 15 values, too...
You initialize an array of int-s, of size 15. The int datatype defaults to 0 (as opposed to its wrapper class Integer which defaults to null), so what you are really doing is creating an int array with 15 0's. So, when you loop through the array and print its content, you will get, well, 15 0's.
The solution is, as implied by others, exchange the loop limitation to the size of the stack (the number of elements actually added), rather than the size of the array.
instead of for(int i=0;i<stackPlaces.length-1;i++), do for(int i=0;i<stackIndex;i++)
Related
I am trying to write a method public static void removeDownTo (StackX stack, long n): It pops all values off the stack down to but not including the first element it sees that is equal to the second parameter. If none are equal, leave the stack empty.
I've tried to section off the problem by popping off the top half of the stack by reaching the n value. But the stack isn't sorted so it causes some problems.
public class StackX {
private int maxSize; // size of stack array
private long[] stackArray;
private int top; // top of stack
//--------------------------------------------------------------
public StackX(int s) // constructor
{
maxSize = s; // set array size
stackArray = new long[maxSize]; // create array
top = -1; // no items yet
}
//--------------------------------------------------------------
public void push(long j) // put item on top of stack
{
if (!isFull())
stackArray[++top] = j; // increment top, insert item
else
System.out.println("Can't insert, stack is full");
}
//--------------------------------------------------------------
public long pop() // take item from top of stack
{
if(!isEmpty())
return stackArray[top--]; // access item, decrement top
else
System.out.print("Error: Stack is empty. Returning -1");
return -1;
}
//--------------------------------------------------------------
public long peek() // peek at top of stack
{
if (isEmpty()){
System.out.print("stack is empty");
}
return stackArray[top];
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return (top == -1);
}
//--------------------
public boolean isFull() // true if stack is full
{
return (top == maxSize-1);
}
//--------------------------------------------------------------
public void removeDownTo (StackX stack, long n){
for(int i = 0; stackArray[i] < n; i++){
stack.pop();
}
for(int j = 0; stackArray[j] <= maxSize; j++){
System.out.println(stackArray[j]);
}
}
}
public class StackApp {
public static void main(String[] args) {
StackX theStack = new StackX(10); // make new stack
theStack.push(20); // push items onto stack
theStack.push(40);
theStack.push(60);
theStack.push(80);
while( !theStack.isEmpty()){ // until it's empty,
theStack.removeDownTo(theStack, 40);
long value = theStack.pop();
System.out.print(value); // display it
System.out.print(" ");
} // end while
} // end main()
} // end class StackApp
I would expect to see 60 80 but instead I get 60 20.
Since you are quite new to programming, your instructor has given you a task that is quite simple to solve. You should stick closely to its words. These words give you the main clues.
You are supposed to define this method:
public static void removeDownTo (StackX stack, long n)
Here, the word static is important. It means that the method should NOT go into the StackX class. (The instructions should mention this somewhere.) If your task had been to add the method to the StackX class, it would have looked like this:
public void removeDownTo (long n)
The difference between these two methods is that the latter has access to all the implementation details of the StackX class, which are the variables maxSize, stackArray and top.
But your task was different, your method should be static, and this means that it doesn't have access to these implementation details. All you can do is call the methods that are marked as public. There are 5 of them, they all start with a lowercase letter. Using only these 5 methods, you are supposed to solve this puzzle, as you wrote:
It pops all values off the stack down to but not including the first element it sees that is equal to the second parameter. If none are equal, leave the stack empty.
By listing the 5 methods above, you can see that a stack allows only very few operations. Think of a large stack of books. You cannot just take one book from the middle, the only thing you can do is to look at the top of the stack. That's the nature of a stack.
You tried:
I've tried to section off the problem by popping off the top half of the stack by reaching the n value. But the stack isn't sorted so it causes some problems.
This task is much simpler than you think. It is not about sorting at all. Follow the words in the instructions more closely. In the end, your removeDownTo method should be 5 lines long, from the beginning to the end. That means inside the braces, there are only 3 lines of code that you need to write.
This is the problem:
You have maps of parts of the space station, each starting at a prison exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the prison is at the top left (0,0) and the door into an escape pod is at the bottom right (w-1,h-1).
Write a function answer(map) that generates the length of the shortest path from the prison door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed.
To Summarize the problem: It is a simple rat in a maze problem with rat starting at (0,0) in matrix and should reach (w-1,h-1). Maze is a matrix of 0s and 1s. 0 means path and 1 means wall.You have the ability to remove one wall(change it from 0 to 1). Find the shortest path.
I've solved the problem but 3 of 5 testcases fail and I don't know what those test cases are. and I'm unable to figure out why. Any help would be greatly appreciated.Thanks in Advance. Here is my code:
import java.util.*;
class Maze{//Each cell in matrix will be this object
Maze(int i,int j){
this.flag=false;
this.distance=0;
this.x=i;
this.y=j;
}
boolean flag;
int distance;
int x;
int y;
}
class Google4_v2{
public static boolean isPresent(int x,int y,int r,int c)
{
if((x>=0&&x<r)&&(y>=0&&y<c))
return true;
else
return false;
}
public static int solveMaze(int[][] m,int x,int y,int loop)
{
int r=m.length;
int c=m[0].length;
int result=r*c;
int min=r*c;
Maze[][] maze=new Maze[r][c];//Array of objects
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
maze[i][j]=new Maze(i,j);
}
}
Queue<Maze> q=new LinkedList<Maze>();
Maze start=maze[x][y];
Maze[][] spare=new Maze[r][c];
q.add(start);//Adding source to queue
int i=start.x,j=start.y;
while(!q.isEmpty())
{
Maze temp=q.remove();
i=temp.x;j=temp.y;
int d=temp.distance;//distance of a cell from source
if(i==r-1 &&j==c-1)
{
result=maze[i][j].distance+1;
break;
}
maze[i][j].flag=true;
if(isPresent(i+1,j,r,c)&&maze[i+1][j].flag!=true)//check down of current cell
{
if(m[i+1][j]==0)//if there is path, add it to queue
{
maze[i+1][j].distance+=1+d;
q.add(maze[i+1][j]);
}
if(m[i+1][j]==1 && maze[i+1][j].flag==false && loop==0)//if there is no path, see if breaking the wall gives a path.
{
int test=solveMaze(m,i+1,j,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i+1][j].flag=true;
}
}
if(isPresent(i,j+1,r,c)&&maze[i][j+1].flag!=true)//check right of current cell
{
if(m[i][j+1]==0)
{
maze[i][j+1].distance+=1+d;
q.add(maze[i][j+1]);
}
if(m[i][j+1]==1 && maze[i][j+1].flag==false && loop==0)
{
int test=solveMaze(m,i,j+1,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i][j+1].flag=true;
}
}
if(isPresent(i-1,j,r,c)&&maze[i-1][j].flag!=true)//check up of current cell
{
if(m[i-1][j]==0)
{
maze[i-1][j].distance+=1+d;
q.add(maze[i-1][j]);
}
if(m[i-1][j]==1 && maze[i-1][j].flag==false && loop==0)
{
int test=solveMaze(m,i-1,j,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i-1][j].flag=true;
}
}
if(isPresent(i,j-1,r,c)&&maze[i][j-1].flag!=true)//check left of current cell
{
if(m[i][j-1]==0)
{
maze[i][j-1].distance+=1+d;
q.add(maze[i][j-1]);
}
if(m[i][j-1]==1 && maze[i][j-1].flag==false && loop==0)
{
int test=solveMaze(m,i,j-1,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i][j-1].flag=true;
}
}
}
return ((result<min)?result:min);
}
public static int answer(int[][] m)
{
int count;
int r=m.length;
int c=m[0].length;
count=solveMaze(m,0,0,0);
return count;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter row size ");
int m=sc.nextInt();
System.out.println("enter column size ");
int n=sc.nextInt();
int[][] maze=new int[m][n];
System.out.println("Please enter values for maze");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
maze[i][j]=sc.nextInt();
}
}
int d=answer(maze);
System.out.println("The maze can be solved in "+d+" steps");
}
}
Found the problem. maze[i][j].flag=true; needs to be put as soon as the cell is visited, inside the if(m[i+1][j]==0) condition. Otherwise, the distance for same cell can be added by more than one cells
Unfortunately it's quite hard to help you because your code is very difficult to read. The variables are generally single characters which makes it impossible to know what they are supposed to represent. Debugging it would be more help than most of us are willing to give :-)
I suggest you go about debugging your code as follows:
Split your solveMaze method into a number of smaller methods that each perform much simpler functions. For example, you have very similar code repeated 4 times for each direction. Work to get that code in a single method which can be called 4 times. Move your code to create the array into a new method. Basically each method should do one simple thing. This approach makes it much easier to find problems when they arise.
Write unit tests to ensure each of those methods do exactly what you expect before attempting to calculate the answer for entire mazes.
Once all the methods are working correctly, generate some mazes starting from very simple cases to very complex cases.
When a case fails, use an interactive debugger to walk through your code and see where it is going wrong.
Good luck.
As title says I need to do the following. But I somehow am getting the wrong answer, perhaps something with the loops is wrong?
And here's what I have coded so far, but it seems to be giving me the wrong results. Any ideas, help, tips, fixes?
import java.util.ArrayList;
public class pro1
{
private String lettersLeft;
private ArrayList<String> subsets;
public pro1(String input)
{
lettersLeft = input;
subsets = new ArrayList<String>();
}
public void createSubsets()
{
if(lettersLeft.length() == 1)
{
subsets.add(lettersLeft);
}
else
{
String removed = lettersLeft.substring(0,1);
lettersLeft = lettersLeft.substring(1);
createSubsets();
for (int i = 0; i <= lettersLeft.length(); i++)
{
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
public void showSubsets()
{
System.out.print(subsets);
}
}
My test class is here:
public class pro1
{
public static void main(String[] args)
{
pro1s = new pro1("abba");
s.createSubsets();
s.showSubsets();
}
}
Try
int numSubsets = (int)java.lang.Math.pow(2,toSubset.length());
for (int i=1;i<numSubsets;i++) {
String subset = "";
for (int j=0;j<toSubset.length();j++) {
if ((i&(1<<j))>0) {
subset = subset+toSubset.substring(j,j+1);
}
}
if (!subsets.contains(subset)) {
subsets.add(subset);
}
}
where toSubset is the string that you wish to subset (String toSubset="abba" in your example) and subsets is the ArrayList to contain the results.
To do this we actually iterate over the power set (the set of all subsets), which has size 2^A where A is the size of the original set (in this case the length of your string).
Each subset can be uniquely identified with a number from 0 to 2^A-1 where the value of the jth bit (0 indexed) indicates if that element is present or not with a 1 indicating presence and 0 indicating absence. Note that the number 0 represents the binary string 00...0 which corresponds to the empty set. Thus we start counting at 1 (your example did not show the empty set as a desired subset).
For each value we build a subset string by looking at each bit position and determining if it is a 1 or 0 using bitwise arithmetic. 1<<j is the integer with a 1 in the jth binary place and i&(i<<j) is the integer with 1's only in the places both integers have a 1 (thus is either 0 or 1 based on if i has a 1 in the jth binary digit). If i has a 1 in the jth binary digit, we append the jth element of the string.
Finally, as you asked for unique subsets, we check if we have already used that subset, if not, we add it to the ArrayList.
It is easy to get your head all turned around when working with recursion. Generally, I suspect your problem is that one of the strings you are storing on the way down the recursion rabbit hole for use on the way back up is a class member variable and that your recursive method is a method of that same class. Try making lettersLeft a local variable in the createSubsets() method. Something like:
public class Problem1
{
private String originalInput;
private ArrayList<String> subsets;
public Problem1(String input)
{
originalInput = input;
subsets = new ArrayList<String>();
}
// This is overloading, not recursion.
public void createSubsets()
{
createSubsets(originalInput);
}
public void createSubsets(String in)
{
if(in.length() == 1)
{
// this is the stopping condition, the bottom of the rabbit hole
subsets.add(in);
}
else
{
String removed = in.substring(0,1);
String lettersLeft = in.substring(1);
// this is the recursive call, and you know the input is getting
// smaller and smaller heading toward the stopping condition
createSubsets(lettersLeft);
// this is the "actual work" which doesn't get performed
// until after the above recursive call returns
for (int i = 0; i <= lettersLeft.length(); i++)
{
// possible "index out of bounds" here if subsets is
// smaller than lettersLeft
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
Something to remember when you are walking through your code trying to think through how it will run... You have structured your recursive method such that the execution pointer goes all the way down the recursion rabbit hole before doing any "real work", just pulling letters off of the input and pushing them onto the stack. All the "real work" is being done coming back out of the rabbit hole while letters are popping off of the stack. Therefore, the first 'a' in your subsets list is actually the last 'a' in your input string 'abba'. I.E. The first letter that is added to your subsets list is because lettersLeft.length() == 1. (in.length() == 1 in my example). Also, the debugger is your friend. Step-debugging is a great way to validate that your code is actually doing what you expect it to be doing at every step along the way.
Why am i getting Time limit exceeded for ans for my this code?
I tried this question on CodeChef.My logic is correct but my answer is showing time limit exceeded , i don't know why ?
http://www.codechef.com/problems/CHEFRP
package test;
import java.io.*;
import java.util.*;
public class Test
{
public static void main(String[] args)throws IOException{
int TESTCASES;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
TESTCASES=Integer.parseInt(br.readLine());
int b=2*TESTCASES,i=0,m,l;
int a;
String[] lines=new String[b];
int[] N=new int[TESTCASES];
int[][] Ai =new int[TESTCASES][100001];
int[] min=new int[TESTCASES];
int flag=0,minusonecase=-1;
int[] sum=new int[TESTCASES]
;
for(a=0;a<b;a++)
{
lines[a]=br.readLine();
if(a%2==0)
{
N[a/2]=Integer.parseInt(lines[a]);
}
if(a%2!=0)
{
StringTokenizer stz=new StringTokenizer(lines[a]);
for(l=0;l<100001;l++)
{
if(stz.countTokens()!=0)
{
Ai[((a-1)/2)][l]=Integer.parseInt(stz.nextToken());
}
else{
break;
}
}
}
}
for(a=0;a<TESTCASES;a++)
{
min[a]=Ai[a][0];
for(l=0;l<N[a];l++)
{
if(min[a]>Ai[a][l])
{
min[a]=Ai[a][l];
}
sum[a]=sum[a]+Ai[a][l];
}
sum[a]=sum[a]+2-min[a];
}
for(a=0;a<TESTCASES;a++)
{
for(l=0;l<N[a];l++)
{
if(Ai[a][l]==1)
{
System.out.println(minusonecase);
flag=1;
break;
}
}
if(flag==1)
{
flag=0;
continue;
}
System.out.println(sum[a]);
}
}
}
Please read the question correctly -
Rupsa recently started to intern under Chef. He gave her N type of ingredients of varying quantity A1, A2, ..., AN respectively to store it. But as she is lazy to arrange them she puts them all in a storage box.
Chef comes up with a new recipe and decides to prepare it. He asks Rupsa to get two units of each type ingredient for the dish. But when she went to retrieve the ingredients, she realizes that she can only pick one item at a time from the box and can know its type only after she has picked it out. The picked item is not put back in the bag.
She, being lazy, wants to know the maximum number of times she would need to pick items from the box in the worst case so that it is guaranteed that she gets at least two units of each type of ingredient. If it is impossible to pick items in such a way, print -1.
You are not handling the case , where one of the ingredients has less than 2 unit, in which case you should be printing -1.
Need to write method called clearStacks() that moves the most recently created robot forward until it reaches a wall picking up all beepers at it goes. The method should return no value
and take no parameters.
It also has a side-effect: the method prints how many beepers the robot picked up in each stack. Supposing there were 3 stacks on a row, the output might look like this:
Beepers: 4
Beepers: 1
Beepers: 7
My problem that I can not write how many beepers the robot picked up in each stack. Only overall amount. I am new in Java..
My code:
void clearStacks() {
int beepers=0;
while(isSpaceInFrontOfRobotClear()) {
moveRobotForwards();
while(isItemOnGroundAtRobot()) {
pickUpItemWithRobot();
++beepers;
println(beepers);
}
}
}
Before checking for a stack, you'll want to reset your count. You'll then need to use a conditional statement to see if any beepers were picked up after clearing a stack (or determining that a stack was not there).
void clearStacks() {
int beepers=0;
while(isSpaceInFrontOfRobotClear()) {
moveRobotForwards();
/* Reset the count of beepers. */
beepers = 0;
/* Pick up any beepers at current spot. */
while(isItemOnGroundAtRobot()) {
/* Pick up beeper, and increment counter. */
pickUpItemWithRobot();
++beepers;
}
/* Check to see if we picked up any beepers.
* if we did, print the amount.
*/
if(beepers > 0){
println(beepers);
}
}
}
Maybe try implementing an array? You could use the first 3 elements to represent the first 3 stacks and then the value could represent how many beepers were picked up in each stack.
int[] beepers = new int[3];
int count = 0;
while(isSpaceInFrontOfRobotClear()) {
moveRobotForwards();
while(isItemOnGroundAtRobot()) {
pickUpItemWithRobot();
beepers[0]++;
if (count > #numberOfBeepers) {
break;
}
}
for (int i: beepers) {
System.out.print(beepers[i] + " ")
}
}
}
Let me know if this answers your question or if it didn't