Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move one step at a time in any of the four directions. Can you rescue the princess?
Input format
The first line contains an odd integer N (3 <= N < 100) denoting the size of the grid. This is followed by an NxN grid. Each cell is denoted by '-' (ascii value: 45). The bot position is denoted by 'm' and the princess position is denoted by 'p'.
Grid is indexed using Matrix Convention
Output format
Print out the moves you will take to rescue the princess in one go. The moves must be separated by '\n', a newline. The valid moves are LEFT or RIGHT or UP or DOWN.
Here is my code:
package challenges;
import java.util.*;
public class Solution {
static void displayPathtoPrincess(int n, int p,String [][] grid){
int botRow=0,botCol=0;
for(int r=0;r<n;r++){
for (int c = 0; c < grid.length; c++) {
if(grid[r][c].equals('m')) {
botRow=r;
botCol=c;
continue;
}
}
if(grid[0][0].equals('P')) {
while(botRow>0) {
botRow--;
System.out.println("UP\n");
}
while(botCol>0) {
botCol--;
System.out.println("LEFT\n");
}
}
else if(grid[0][p-1].equals('P')) {
while(botRow>0) {
System.out.println("UP\n");
botRow--;
}
while(botCol<p-1) {
botCol++;
System.out.println("RIGHT\n");
}
}
else if(grid[n-1][0].equals('P')) {
while(botRow<n-1) {
botRow++;
System.out.println("DOWN\n");
}
while(botCol>0) {
botCol--;
System.out.println("LEFT\n");
}
}
else if(grid[n-1][p-1].equals('P')) {
while(botRow<n-1) {
botRow++;
System.out.println("DOWN\n");
}
while(botCol<p-1) {
botCol++;
System.out.println("RIGHT\n");
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
n=m;
int j=0;
String grid[][] = new String[m][n];
for(int i = 0; i < m; i++) {
while(j<n){
grid[i][j] = in.next();
j++;
}
}
displayPathtoPrincess(m,n,grid);
}
}
Its giving Null Pointer Exception.can anyone please tel what am i doing wrong in here?
Try this solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine());
char grid[][] = new char[m][m];
for(int i = 0; i < m; i++)
{
String line = br.readLine();
grid[i] = (line.trim()).toCharArray();
}
displayPathtoPrincess(m, grid);
}
static void displayPathtoPrincess(int m, char[][] grid)
{
int botRow = 0, botCol = 0, princessRow = 0, princessCol = 0;
// Get bot and princess coordinates
for (int r = 0; r < m; r++)
{
for (int c = 0; c < grid.length; c++)
{
if (grid[r][c] == 'm' || grid[r][c] == 'M')
{
botRow = r;
botCol = c;
}
else if (grid[r][c] == 'p' || grid[r][c] == 'P')
{
princessRow = r;
princessCol = c;
}
}
}
// Move the bot up or down till bot reaches same row
if( princessRow < botRow )
{
while(botRow != princessRow)
{
botRow--;
System.out.println("UP");
}
}
else if( princessRow > botRow )
{
while(botRow != princessRow)
{
botRow++;
System.out.println("DOWN");
}
}
// Move the bot left or right till bot reaches same column
if( princessCol < botCol )
{
while(botCol != princessCol)
{
botCol--;
System.out.println("LEFT");
}
}
else if( princessCol > botCol )
{
while(botCol != princessCol)
{
botCol++;
System.out.println("RIGHT");
}
}
}
}
Ok, no offence but this code is a mess.
I know what I will answer won't be exactly what you want, but it might be very helpful for you in the future.
What would I change? (After you change all of this, the error will more likely become apparent or it will be clear enough to ask for help)
First: Variable types.
This is just a tiny detail, but I don't like the way you did it; why use a String if every cell will be represented by a char?
Every time you create a variable (or an Array, or anything at all) think about what you need it to store, and create the variable in a way it will store what you need. If you needed it to store if something is true or false, you wouldn't create a String variable and store "true" or "false", you would use a boolean.
Apply this every time and you will improve faster.
Second: use functions.
Functions are a great way to abstract yourself from the implementation details.
I mean, you can easily see the difference between something like your code, and something like:
static void displayPathtoPrincess(int n, int p,char [][] grid){
Point bot;
Point princess;
getInitialPositions(bot, princess, grid);
Point dif = getRelativePrincessPosition(bot, princess);
while (!bot.equals(princess)) {
switch (dif.y) {
case UP:
move (UP_MOVEMENT);
break;
case DOWN:
move (DOWN_MOVEMENT);
break;
}
switch (dif.x) {
case LEFT:
move(LEFT_MOVEMENT);
break;
case RIGHT:
move(RIGHT_MOVEMENT);
break;
}
}
}
(And then implement the necessary methods, and create the constants, that is something pretty easy to do)
Third: use the appropriate loop every time.
If you know you want to go from j = 0, while j < n, increasing j every iteration; that's not called a while, that's called a for. (Also, as someone else commented in their answer, you forgot to restart the j; so it only goes in once.
Finally: Let's go with your error now.
I believe your code might be pretty buggy and not give you the desired output, but the NullPointerException is something more specific.
Since you don't use the appropriate loop in the main, for j, and you forgot to restart it's value, you didn't fill the whole array.
When you try to read a value you didn't fill (in the for where you find the robot's position), that value is null, and the value for some rows will be null too; hence the NullPointerException (because you try to access the value of a null array).
While taking input you have to make j =0 every time you are coming out of while loop as
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
n=m;
int j=0;
String grid[][] = new String[m][n];
for(int i = 0; i < m; i++) {
j = 0;
while(j<n){
grid[i][j] = in.next();
j++;
}
}
i remains 0 due to this mistake.
You should put print statement to check why are you getting error.
here is the solution..
import java.util.*;
public class Solution {
static void displayPathtoPrincess(int n, int p, String[][] grid) {
int botRow = 0, botCol = 0;
for (int r = 0; r < n; r++) {
for (int c = 0; c < grid.length; c++) {
if (grid[r][c].equalsIgnoreCase("m")) {
botRow = r;
botCol = c;
}
}
if (grid[0][0].equalsIgnoreCase("P")) {
while (botRow > 0) {
botRow--;
System.out.println("UP\n");
}
while (botCol > 0) {
botCol--;
System.out.println("LEFT\n");
}
} else if (grid[0][p - 1].equalsIgnoreCase("P")) {
while (botRow > 0) {
botRow--;
System.out.println("UP\n");
}
while (botCol < p - 2) {
botCol++;
System.out.println("RIGHT\n");
}
} else if (grid[n - 1][0].equalsIgnoreCase("P")) {
while (botRow < n - 2) {
botRow++;
System.out.println("DOWN\n");
}
while (botCol > 0) {
botCol--;
System.out.println("LEFT\n");
}
} else if (grid[n - 1][p - 1].equalsIgnoreCase("P")) {
while (botRow < n - 2) {
botRow++;
System.out.println("DOWN\n");
}
while (botCol < p - 2) {
botCol++;
System.out.println("RIGHT\n");
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
int j;
String grid[][] = new String[m][m];
for(int i = 0; i < m; i++) {
for(j=0;j<m;j++){
grid[i][j] = in.next();
}
}
displayPathtoPrincess(m,m,grid);
}
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static void nextMove(int n, int r, int c, String [] grid){
int xcord=0;
int ycord=0;
for ( int i = 0 ; i <n-1; i++){
String s = grid[i];
xcord=i;
for(int x =0; x<=n-1;x++){
if(s.charAt(x)=='p'){
ycord=x;
if(xcord==r){
if(ycord>c){System.out.println("RIGHT");return;}
else {System.out.println("LEFT");return;}
}else if(xcord<r){System.out.println("UP");return;}
else{ System.out.println("DOWN");return;}
}
}
}
System.out.println(xcord);
System.out.println(ycord);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n,r,c;
n = in.nextInt();
r = in.nextInt();
c = in.nextInt();
in.useDelimiter("\n");
String grid[] = new String[n];
for(int i = 0; i < n; i++) {
grid[i] = in.next();
}
nextMove(n,r,c,grid);
}
}
You might wish to take a look at the following code in Java:
import java.util.Scanner;
public class Solution {
/*
*
*/
static void printPath(int n, String moves) {
for (int i = n / 2; i >= 0; i -= 2) {
System.out.println(moves);
}
}
/*
*
*/
static void displayPathtoPrincess(int n, String [] grid){
// **** princess # top left ****
if (grid[0].substring(0, 1).equals("p")) {
printPath(n, "UP\nLEFT");
}
// **** princess # top right ****
else if (grid[0].substring(n - 1, n).equals("p") ) {
printPath(n, "UP\nRIGHT");
}
// **** princess # bottom right ****
else if (grid[n - 1].substring(n - 1, n).equals("p")) {
printPath(n, "DOWN\nRIGHT");
}
// **** princess # bottom left ****
else {
printPath(n, "DOWN\nLEFT");
}
}
/*
* Test code
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m;
m = in.nextInt();
String grid[] = new String[m];
for(int i = 0; i < m; i++) {
grid[i] = in.next();
}
// **** ****
in.close();
// **** ****
displayPathtoPrincess(m,grid);
}
}
I'm working on an assignment that takes a data file with a number matrix and determines if it is a magic square. If it is then it also needs to report the sum of the rows and columns. With the output:
The matrix is a magic square.
The sum of all the rows and columns is 34.
I'm not sure how to go about this with one method, I feel like its asking me to return 2 values. The closest I have came is by adding a System.out.println with the sum at the end of my method when it returns true.
But the issue with that is that my output is backwords:
The sum of all the rows and columns is 34.
The matrix is a magic square.
How do I get the sum when I've only been asked to create one method? Below is my code, the instructor gave the bottom 3 methods so I'm only concerned with the first 2.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class chp8magic
{
public static void main(String args[])
{
int matrix[][] = initMatrix();
printData(matrix);
if (isMagic(matrix)) {
System.out.println("The matrix is a magic square.");
}
else {
System.out.println("Not a magic square");
}
}
public static boolean isMagic(int[][] mat)
{
int n = mat.length;
int nSquare = n*n;
int M = (n*n*(n*n+1)/2)/n;
int sumRow = 0, sumColoumns = 0, sumPriDiag = 0, sumSecDiag = 0;
boolean[] flag = new boolean[n*n];
for(int row = 0; row < n; row++){
sumRow = 0;
sumColoumns = 0;
for(int col = 0; col < n; col++)
{
if( mat[row][col] < 1 || mat[row][col] > nSquare )
return false;
if(flag[mat[row][col]-1] == true)
return false;
flag[mat[row][col]-1] = true;
sumRow += mat[row][col];
sumColoumns += mat[col][row];
}
sumPriDiag += mat[row][row];
sumSecDiag += mat[row][n-row-1];
if(sumRow!=M || sumColoumns!=M)
return false;
}
if(sumPriDiag!=M || sumSecDiag!=M)
return false;
else
return true;
}
public static int[][] initMatrix()
{
int matrix[][];
Scanner filein = null;
try {
filein = new Scanner(new File("matrix.txt"));
int numRows = Integer.parseInt(filein.nextLine());
matrix = new int[numRows][];
parseData(matrix, filein);
filein.close();
return matrix;
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
if(filein != null)
filein.close();
return null;
}
}
public static void parseData(int matrix[][], Scanner in)
{
for(int r = 0; r < matrix.length; r++)
{
String splitLine[] = in.nextLine().split(" ");
matrix[r] = new int[splitLine.length];
for(int c = 0; c < matrix[r].length; c++){
matrix[r][c] = Integer.parseInt(splitLine[c]);
}
}
}
public static void printData(int matrix[][])
{
for(int r = 0; r < matrix.length; r++){
for(int c = 0; c < matrix[r].length; c++){
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
Probably you just need to do:
System.out.println("is magic: " + isMagic);
System.out.ptintln("sum: " + sum);
However this is not really returning the values, just printing them. To return two values there are several options. You could return an object:
public class MagicSquareProperties {
private boolean magic;
private int sum;
public MagicSquareProperties(boolean magic, int sum) {
this.magic = magic;
this.sum = sum;
}
public boolean isMagic() {
return magic;
}
public int getSum() {
return sum;
}
}
// now to return both values: return new MagicSquareProperties(true, 34);
But in my opinion the best solution would be the following:
Create a class MagicSquare.
Add property declarations (e.g. private int sum).
Add a constructor, for example MagicSquare(File file), this constructor reads the file and populates the properties.
Add getters and setters if needed (e.g. getSum())
Execute the main method in another class and call new MagicSquare(...) to create a magic square object. Afterwards you can call the getters on the object whenever you need the value.
The program I am working on is a simple shipping program. What I am having difficulty with is populating a multidimensional array factoring in certain variables.
Example
320 items need to be shipped out to 1 receiver using different box sizes.
XL can hold 50 items
LG can hold 20 items
MD can hold 5 items
SM can hold 1 items
Use the least number of boxes so far.
Code
This is my code so far.
import java.util.Scanner;
public class Shipping {
public static void main(String [] args) {
Scanner kbd = new Scanner(System.in);
final int EXTRA_LARGE = 50;
final int LARGE = 20;
final int MEDIUM = 5;
final int SMALL = 1;
String sBusinessName = "";
int iNumberOfGPS = 0;
int iShipmentCount = 0;
displayHeading(kbd);
iShipmentCount = enterShipments(kbd);
int[][] ai_NumberOfShipments = new int [iShipmentCount][4];
String[] as_BusinessNames = new String [iShipmentCount];
for (int iStepper = 0; iStepper < iShipmentCount; iStepper++) {
sBusinessName = varifyBusinessName(kbd);
as_BusinessNames[iStepper] = sBusinessName;
iNumberOfGPS = varifyGPS(kbd);
calculateBoxes(ai_NumberOfShipments[iStepper],iNumberOfGPS, EXTRA_LARGE, LARGE, MEDIUM, SMALL);
}
//showArray(as_BusinessNames);
}
public static void displayHeading(Scanner kbd) {
System.out.println("Red River Electronics");
System.out.println("Shipping System");
System.out.println("---------------");
return;
}
public static int enterShipments(Scanner kbd) {
int iShipmentCount = 0;
boolean bError = false;
do {
bError = false;
System.out.print("How many shipments to enter? ");
iShipmentCount = Integer.parseInt(kbd.nextLine());
if (iShipmentCount < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
bError = true;
}
} while (bError == true);
return iShipmentCount;
}
public static String varifyBusinessName(Scanner kbd) {
String sBusinessName = "", sValidName = "";
do {
System.out.print("Business Name: ");
sBusinessName = kbd.nextLine();
if (sBusinessName.length() == 0) {
System.out.println("");
System.out.println("**Error** - Name is required\n");
} else if (sBusinessName.length() >= 1) {
sValidName = sBusinessName;
}
} while (sValidName == "");
return sValidName;
}
public static int varifyGPS(Scanner kbd) {
int iCheckGPS = 0;
int iValidGPS = 0;
do {
System.out.print("Enter the number of GPS receivers to ship: ");
iCheckGPS = Integer.parseInt(kbd.nextLine());
if (iCheckGPS < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
} else if (iCheckGPS >= 1) {
iValidGPS = iCheckGPS;
}
} while(iCheckGPS < 1);
return iValidGPS;
}
public static void calculateBoxes(int[] ai_ToFill, int iNumberOfGPS) {
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++)
}
//public static void showArray( String[] ai_ToShow) {
// for (int iStepper = 0; iStepper < ai_ToShow.length; iStepper++) {
// System.out.println("Integer at position " + iStepper + " is " + ai_ToShow[iStepper]);
// }
//}
}
Change your definition of calculateBoxes() to also take an array that represents the volume of each of the boxes (in your case this will be {50, 20, 5, 1}:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
// while the remaining items to pack is greater than the current box size
while(iNumberOfGPS >= boxVolumes[iStepper]) {
// increment the current box type
ai_ToFill[iStepper]++;
// subtract the items that just got packed
iNumberOfGPS -= boxVolumes[iStepper];
}
}
}
Another way of calculating this (using / and % instead of a while loop) would be:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
if(iNumberOfGPS >= boxVolumes[iStepper]) {
// calculate the number of boxes that could be filled by the items
ai_ToFill[iStepper] = iNumberOfGPS/boxVolumes[iStepper];
// reset the count of items to the remainder
iNumberOfGPS = iNumberOfGPS%boxVolumes[iStepper];
}
}
}
I am trying to wrtie java application that adds up to 5 long numbers using LinkedLists. At the end of the run I get this:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index:
0, Size: 0
at java.util.LinkedList.checkElementIndex(LinkedList.java:555) at java.util.LinkedList.remove(LinkedList.java:525) at
Assignment1.LongNumbers.remove(LongNumbers.java:33) at
Assignment1.LongNumbers.main(LongNumbers.java:92)
Here is the code:
import java.util.*;
/**
*
* #author .....
*/
public class LongNumbers
{
private List<Integer> [] theLists;
public LongNumbers() {
this.theLists = new LinkedList[6];
for (int i=0; i<6; i++)
this.theLists[i]= new LinkedList<>();
}
public void add(int location, int digit) {
//add digit at head of LinkedList given by location
theLists[location].add(digit);
}
public int remove(int location) {
//remove a digit from LinkedList given by location
return theLists[location].remove(location); //LongNumbers.java:33
}
public boolean isEmpty(int location) {
//check for an empty LinkedList given by location
return theLists[location].isEmpty();
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
//Local Variables
int digit;
int carry = 0;
int numberAt = 0;
int largestNumLength = 0;
char[] digits;
String number;
boolean userWantstoQuit = false;
LongNumbers Lists = new LongNumbers();
System.out.println("The program will enter up to 5 numbers and add them up.");
System.out.println();
while(!userWantstoQuit && numberAt != 5){
System.out.print("Enter a number, enter -1 to quit entry phase: ");
number = stdIn.nextLine();
if((number.compareTo("-1")) == 0)
userWantstoQuit = true;
else{
digits = new char[number.length()];
for(int i=0;i<number.length();i++)
digits[i] = number.charAt(i);
for(int i=0;i<number.length();i++){
int tempValue = digits[i] - 48;
try{
Lists.add(numberAt, tempValue);
}
catch(NumberFormatException nfe){
System.out.println("Invalid Input. Please try again.");
break;
}
if(i == (number.length() - 1))
numberAt++;
if(number.length() > largestNumLength)
largestNumLength = number.length();
}
}
}
for(int j=0;j<largestNumLength;j++){
int tempDigit = 0;
int index = 0;
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0); //LongNumbers.java:99
}
index++;
}
digit = carry + tempDigit;
if(j < numberAt){
carry = digit/10;
digit = digit%10;
}
Lists.add(5, digit);
}
System.out.print("The sum of the numbers is: ");
for(int i=0;i<Lists.theLists[5].size();i++){
System.out.print(Lists.theLists[5].get(i));
}
System.out.println();
System.out.println();
System.out.println();
}//end main
}//end class
For starters, I don't think you can have an array of List<E> objects...
You should also make sure your list is initialized and has an item at the given location.
So your method might look something like this:
public int remove(int location)
{
if(theLists != null)
if(theLists.size() > location)
return theLists.remove(location);
return 0;
}
If you need 2 dimensions of lists, you could try using List<List<E>>
Treat all E as Integer.
Look at the code here:
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0); //LongNumbers.java:99
}
index++;
}
You are checking whether the first element of the index'th list is not null. If that is true, you are adding it and call the remove method. However, what if you already processed the first list and index'th value is 1? In that case theLists[1].get(0) != null is true, but Lists.remove(0) passes 0 as location. Take a look at this code:
public int remove(int location) {
//remove a digit from LinkedList given by location
return theLists[location].remove(location); //LongNumbers.java:33
}
In the scenario I have described, location is 0. But your 0'th list is already empty...
EDIT: Rewrite the remove method, like this:
public int remove(int location, int index) {
//remove a digit from LinkedList given by location
return theLists[index].remove(location); //LongNumbers.java:33
}
And whenever you call this method, pass the index of the list to work with. Example:
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0, index); //LongNumbers.java:99
}
index++;
}
Finally: In the future, please, structure your code, it was a real pain to read it in this, unstructured state, read about how to code.
I am writing a slot machine class that generates 3 arrays of 3 random numbers and checks if all of the numbers match, if so they are declared a winner. I have written another program to run 1000 slot machines and count the winners. The problem I am facing is that it always gives me 0 winners. Any help? Here is the code for each:
the SlotMachine class
import java.util.*;
public class SlotMachine{
private int[] row1 = new int[3];
private int[] row2 = new int[3];
private int[] row3 = new int[3];
public SlotMachine() {
playMachine();
}
public void playMachine() {
Random rand = new Random();
for (int counter = 0; counter < 3; counter++) {
row1[counter] = rand.nextInt(10);
}
for (int counter = 0; counter < 3; counter++) {
row2[counter] = rand.nextInt(10);
}
for (int counter = 0; counter < 3; counter++) {
row3[counter] = rand.nextInt(10);
}
}
public boolean isWinner() {
if (row1[0] == row1[1]) {
if (row1[0] == row1[2]) {
return true;
}
}
if (row2[0] == row2[1]) {
if (row2[0] == row2[2]) {
return true;
}
}
if (row3[0] == row3[1]) {
if (row3[0] == row3[2]) {
return true;
}
}
return false;
}
}
The win counter:
import java.util.*;
public class Play1000SlotMachines {
public static void main(String[] args) {
SlotMachine slotMachine = new SlotMachine();
int count = 0;
for (int i = 0; i < 1000; i++) {
if (slotMachine.isWinner() == true) {
count = count + 1;
}
}
System.out.println("From 1000 slot machines, " + count + " were winners.");
}
}
You never re-roll the slot machine. I also changed the name of the method, to reflect this implementation. If you would rather play 1000 different slot machines, move the declaration of a new slot machine into the for loop. This will create 1000 different instances of the slot machine class, rather than the below implementation where a single instance of a slot machine is created which is then played 1000 times. An important distinction.
public class PlaySlotMachine1000Times {
public static void main(String[] args) {
SlotMachine slotMachine = new SlotMachine();
int count = 0;
for (int i = 0; i < 1000; i++) {
slotMachine.playMachine();
if (slotMachine.isWinner())
count++;
}
System.out.println("From 1000 slot machines, " + count + " were winners.");
}
}