Count beepers in stacks in Java - java

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

Related

Java recursive function below what is the problem?

public static int score(int[][] array, int win, int turn) {
int score = 0;
if (GamePrinciples.gameEnd(array, win)) {
if (GamePrinciples.draw(array)) {
score = 0;
} else if (GamePrinciples.winningBoard(array, win)[0] == 1) {
score = 1;
} else {
score = -1;
}
} else {
for (int[][] i : children(array, win, turn)) {
score += score(i, win, GamePrinciples.nextPlayer(turn));
}
}
return score;
}
briefly this program is part of my minimax algorithm. So the problem is that I get a stack over flow. Where am I going wrong?
if an array is in ending mode then if it is a draw it gives a score of zero if player one wins then a score of one and if player two wins it gives a score of two.
if the array is however not in the ending state we get the children of the array (immediate children that is the boards that result from the current board with only one move). The score of the board will be the sum of the score of each of its children. The logic seems okay and the other methods such as children, nextPlayer, winningBoard, draw all work fine with testing. So I am guessing there is problem with this kind of recursive implementation. Can anyone help? Thanks in advance
Your code seems wrong in the loop:
for (int[][] i : children(array, win, turn)) {
I haven’t tested, but you should call the method children() outside the for.
By calling the method within the for clause, you are always returning the initial array instead of iterating through it.
So try putting the children() method return to a variable and iterate through this variable.
Something like:
… c = children(…)
for(int[][] i : c) {
…

Shortest path in Rat in a Maze with option to remove one wall

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.

Why do I get a NullPointerException for my SmarterSorter program?

I am using BlueJ with Karel the Robot.
The program is called SmarterSorter, and here are the instructions: (I need a bit of help with the program over all, not just with the NullPointerException).
Background: there are an unknown number of vertical piles of beepers (no gaps) – each vertical pile has an unknown number of beepers in it (one beeper per corner – no gaps). The bottom beeper of the left-most pile is always at the origin.
I’m intentionally not giving you the algorithm in bullet form (so you can’t just turn the bullets into methods). I’m pretending I’m an end-user (i.e., a quasi-intellect in terms of computer programming – so, I’m going to describe the problem in English).
So, here’s the algorithm:
The SmarterSorterRobot(SSR) does the sorting. She, however, has some helpers (delegates) – the PutterRobot(PUR) and the PickerRobot(PIR). The SSR knows that she always starts off facing East and is standing on the bottom-most beeper in the left-most vertical pile. She begins by walking along the bottom row of all the vertical piles and stopping when she reaches an empty corner. Then, she creates all those PIRs and then, after they are all created, commands each one in turn to pick up all of the beepers in their respective pile(so, for example, if the PIR in the first vertical pile had 5 beepers above him, he would be standing 6 corners above where he was, having picked up 6 beepers). SSR should now query each PIR for the number of beepers it picked up and she should store those counts as she gets them into a java array of ints. She should then sort that array (see API for Arrays). She should now, working left to right again, create a PUR at the bottom of the first soon-to-be-created pile of beepers – the PUR should know how many beepers it is about to put(the smallest number from the recently sorted array). The PUR should then put all the beepers and go HOME (described below) in the most efficient manner possible. The SSR should now create a second PUR and have it do the same – continue until all piles have been placed (i.e., all piles are now in sorted non-descending order and all the PURs are at HOME position). The SSR should now ask each PIR to go HOME. And, finally, the SSR should now go HOME.
HOME: home is the corner directly North of the top-most beeper in the left-most vertical column.
And here is my code:
import java.util.Arrays;
public class SmarterSorterRobot extends GoHomeBot
{
public SmarterSorterRobot(int av, int st, Direction dir, int beeps)
{
super(av, st, dir, beeps);
}
public int x =1;
private PickerRobot [] robot;
private PutterRobot [] bot;
private int numBeeps;
private int [] myPutterRobots;
private int [] numBeepers;
public int getNumBeeps()
{
return numBeeps;
}
public void sortBeepers()
{
turnRight();
countNumberOfRows();
robot = new PickerRobot [x];
createPickerRobots();
pickLotsOfBeepers();
transferToBeepers();
sortTheBeepers(numBeepers);
robot [x].goHome();
this.goHome();
}
public void countNumberOfRows()
{
while(nextToABeeper())
{
move();
x++;
}
}
public void createPickerRobots()
{
for (int i=1;i<robot.length;i++)
{
robot [i]= new PickerRobot (1,i,North,0);
}
}
public void pickBeepers()
{
while(nextToABeeper())
{
pickBeeper();
move();
numBeeps++;
}
}
public void pickLotsOfBeepers()
{
for (int i=1; i<robot.length; i++)
{
robot [i].pickBeepers();
}
}
public int[] transferToBeepers()
{
int [] numBeepers = new int [x];
for (int i=0; i<numBeepers.length;i++)
{
numBeepers [i] = ;
}
Arrays.sort (numBeepers);
return numBeepers;
}
public void sortTheBeepers(int [] numBeepers)
{
for (int i=0; i<numBeepers.length; i++)
{
PutterRobot robespierre = new PutterRobot (1, i, North, numBeepers [i]);
while(anyBeepersInBeeperBag())
{
putBeeper();
}
goHome();
}
}
}
I get a NullPointerException on the first line of the sortTheBeepers method.
I cannot figure out why.
Thank you for your help!
Let us look at the following method:
public void sortBeepers()
{
// ..
transferToBeepers();
sortTheBeepers(numBeepers);
// ..
}
It calls the method transferToBeepers() which is doing something with a local numBeepers array and then you're calling sortTheBeepers with a different (this time global) variable numBeepers. This numBeepers version is still null, because it was never initialized before, therefore the line for (int i=0; i<numBeepers.length; i++) throws the NullPointerException due to the call numBeepers.length (i.e. null.length).
So how can you fix that ... look at the method transferToBeepers again. As you can see, it returns the mentioned local version of numBeepers, but you're currently ignoring that returned value. So change the above lines as follows:
public void sortBeepers()
{
// ..
numBeepers = transferToBeepers();
sortTheBeepers(numBeepers);
// ..
}
That way, you're initializing the global numBeepers version with the result of transferToBeepers and it won't be null during the sortTheBeepers(numBeepers) call.
Btw, you should also fix the numBeepers [i] = ; line in the transferToBeepers method.

Can I manipulate the way that variables change in Java?

If the die shows a 6, the player doesn't move at all on this turn and also forfeits the next turn.
To accomplish this, I have tried an integer type warning marker variable for the player and an integer type time counter variable.
If the die shows 6, I want to increment the warning marker variable by 1 during the first run(and have the while loop do nothing), then keep the value at 1 during the second run (while loop will not work), then lower it back down to 0 for the third run of the while loop (so the while loop will work). The marker will stay at zero unless the die shows a 6 again, after which the same process will repeat.
I have a while loop like this:
while the warning marker is equal to 0 {
Do Stuff
if the die shows a 6, the warning marker increases by 1.
the time counter also increases by 1.
}
How do I manipulate the variables to get the result that I need? Or is my partially complete method absolutely off in terms of logic?
Thanks.
Can u tell me if this works for you?
flag=true;
while condition{
if flag==true{
if die == 6
{
flag=false;
continue;}
}
else { Do STUFF }
} else
{
flag==true;
}
}
I think you want to reword this problem.
This is what I understood. You have a warning marker.
You have a loop that checks whether the marker is 0, if it is then you do something.
If the die is a six, you will increase the warning marker. If its new value is 3, then you will reset it to 0. Meanwhile, the time counter is always increasing.
If this is correct, I think you want something like:
int warningMarker = 0;
int timeMarker = 0;
while (true) {
if (die == 6) {
++warningMarker;
if (warningMarker == 3) {
warningMarker = 0;
}
}
if (warningMarker == 0) {
doSomething();
}
++timeMarker;
}
Java is Object-Oriented Pragramming language. Use this feature.
See following pseudocode and let me know if you have problem in undestanding it.
Create a class Player as following:
class Player
{
boolean skipChance = false;
... // Other fields
... //
}
Change your while as following:
while(isGameOn())
{
Player p = getCurrentPlayer();
if( ! p.skipChance)
{
int val = p.throwDice();
if(val == 6)
{
p.skipChance = true;
continue; // control moves to while.
}
// Do stuff
}
else
{
p.skipChance = false;
}
}

How to show nothing on the console via System.out.println?

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++)

Categories

Resources