I wrote this code but every time I try to show the output to the user by a System.out.print statement something goes wrong.
The purpose of the code is to check if the array is "palindromic".
import java.util.Scanner;
public class u {
public static void main(String[] args) {
int [] arr = {1,2,3,4,3,2,1};
int counter1 = 0,counter2 = arr.length-1;
int x = arr.length/2;
while (counter1 < x ) {
if (arr[counter1] == arr [counter2]){
counter1++;
counter2--;
} else {System.out.println(":("); break;}
}
System.out.println("Bingo!");
}}
If the problem is that the program always prints "Bingo!" it's because break only ends the while loop. And the "Bingo!" line is outside the while loop so it will still be called. You can avoid this by either change break to return. You can also use labels:
x: {
while(...) {
...
else break x;
}
System.out.println("Bingo!");
}
import java.util.Scanner;
public class u {
public static void main(String[] args) {
boolean d = false;
int [] arr = {2,9,3,4,4,3,9,2};
int counter1 = 0,counter2 = arr.length-1;
int x = arr.length/2;
while (counter1 < x ) {
d = false;
if (arr[counter1] == arr [counter2]){
counter1++;
counter2--;
d = true;
} else break;
}
if (d)
System.out.println("Bingo!");
else System.out.println(":(");
}}
Related
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 am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?
I know it may be weird question but I'm really stuck. I have simple program with two classes. I need pass array from class A to class B. I did it but I cannot test it because I have no idea how to run program. When I click on the run then only one class started. I wanted test whole program and cannot find anything how to do it. Is there any command or something which say run class A and then class B? Without it I cannot test class B because values from Array (class A) are not loaded :/ Hope you understand what I mean.
I'm using eclipse.
Thanks!
Class MarkCalculator
import java.util.Scanner;
public class MarkCalculator {
public static int[] exam_grade = new int[6];
public static int[] coursework_grade = new int[6];
public static int[] coursework_weight = new int[2];
public static int[] module_points = new int[6];
public static String module_grade, holder;
public static int counter1 = 0, counter2 = 0;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
for (int i=0; i<3; i++){
System.out.printf(i+1+". Modelue"+" Enter grade of exam:");
while (!input.hasNextInt() ){
System.out.printf("Enter only numbers! Enter grade of your exam: ");
input.next();
}
exam_grade[i]=input.nextInt();
System.out.printf(i+1+". Modelue"+" Enter grade of coursework:");
while (!input.hasNextInt()){
System.out.printf("Enter only numbers! Enter grade of your coursework: ");
input.next();
}
coursework_grade[i]=input.nextInt();
}
computeMark(coursework_grade, exam_grade, module_points);
// calculate module grade
for(int i = 0 ;i < 3; i++){
if (module_points[i] < 35){
System.out.println(i+1+".Module: Fail");
}
else if (module_points[i] >= 35 && module_points[i] <= 40){
System.out.println(i+1+".Module: Pass by compensation");
counter1++;
}
else {
System.out.println(i+1+".Module: Pass");
counter2++;
}
}
holder = computeResult(module_points, counter1,counter2, module_grade);
System.out.println("Your stage result is: "+ holder);
input.close();
}
public static int[] computeMark (int coursework_grade[], int exam_grade[], int module_points[]){
coursework_weight[0]= 50;
coursework_weight[1]= 50;
for(int i=0;i<3;i++)
{
if (coursework_grade[i] < 35 || exam_grade[i] < 35){
module_points[i]=(coursework_grade[i]*coursework_weight[0] + (exam_grade[i]*(100-coursework_weight[1])))/100;
if (module_points[i] > 35){
module_points[i] = 35; }
else {
module_points[i] = 0;
}
}
else {
module_points[i]=((coursework_grade[i]*coursework_weight[0] + (exam_grade[i]*(100-coursework_weight[1])))/100); }
}
return module_points;
}
public static String computeResult (int module_points[], int counter1, int counter2, String module_grade ){
int sum = 0;
double average = 0;
for (int i = 0; i < 3; i++){
sum = sum + module_points[i];
average = sum / 3;
}
for (int i = 0; i < 3; i++){
if (counter2 == 3){
module_grade = "Pass";
}
else if (average >= 40 && counter1 <= 2) {
module_grade = "Pass by compensation";
}
else {
module_grade = "Fail";
}
}
return module_grade;
}
}
Class StudentChart
public class StudentChart {
public static void main(String[] args) {
for (int i = 0; i < 3; i++){
System.out.println(MarkCalculator.coursework_weight);
}
}
}
You only need one main method.
class A {
String s;
public A(String s){
this.s = s;
}
}
public class B {
public static void main(String[] args){
A a = new A("Hello");
System.out.println(a.s + " world!");
}
}
class B will be the application program, the one with the main method. It will get values from class A. class A does not need to run for class B app to work, even though it uses values from class A.
You can have a method with a different name in another class, and call that method from your main method.
Do not call it public static void main though - that should only be used for standalone programs. If the method requires some other code to be run prior to it, it should not be the main method of a Java program.
I guess you all know the "strawberry" problem that some give you in job interviews, where you need to calculate the path between 2 corners of a 2D array that you can only move up or to the right and you have the calculate the maximum valued path.
I have a perfectly working code that does it in Recursion, but it's complexity is to high.
i also solved the problem in the "for loop" solution that does it in O(n^2) complexity.
but in this solution i just couldn't figure out a way to print the route like i did in the recursion solution.
This is my code (it is quite long to read here so i guess you should copy,compile and run).
look at the results of the recursion solution, BTW - The path needs to be from the left bottom corner to the right upper corner
I want to print the route the same way in the better solution:
public class Alg
{
public static void main(String args[])
{
String[] route = new String[100];
int[][]array = {{4,-2,3,6}
,{9,10,-4,1}
,{-1,2,1,4}
,{0,3,7,-3}};
String[][] route2 = new String[array.length][array[0].length];
int max = recursionAlg(array,array.length-1,0,route);
int max2 = loopAlg(array,array.length-1,0,route2);
System.out.println("The max food in the recursion solution is: "+max);
System.out.println("and the route is: ");
printRouteArray(route);
System.out.println("The max food in the loop solution: "+max2);
System.out.println("The route is: ");
//SHOULD PRINT HERE THE ROUTE
}
public static int loopAlg(int [][] arr,int x, int y, String[][] route)
{
int n=0;
int[][]count = new int[arr.length][arr[0].length];
for(int i = x; i>=0 ; i--)
{
for(int j = 0; j<arr[0].length; j++)
{
if (i==x && j==0) {count[i][j]=arr[i][j];}
else if (i == x) { count[i][j]=count[i][j-1]+arr[i][j];}
else if (j == 0) { count[i][j]=count[i+1][j]+arr[i][j]; }
else{
if (count[i][j-1]>count[i+1][j]) {count[i][j]=count[i][j-1]+arr[i][j];}
else { count[i][j]= count[i+1][j]+arr[i][j];}
}
}
}
return count[0][arr[0].length-1];
}
public static int recursionAlg(int [][] arr, int x, int y,String[] route)
{
return recursionAlg(arr,0,x,y,arr[0].length-1,route,0);
}
public static int recursionAlg(int[][]arr,int count,int x, int y, int max_y, String[] route, int i)
{
if (x == 0 && y == max_y) {return count;}
else if (x == 0) {
route[i]="Right";
return recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1);
}
else if (y==max_y){
route[i]="Up";
return recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1);
}
else if (recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1)>recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1))
{
route[i]="Up";
return recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1);
}
else
{
route[i]="Right";
return recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1);
}
}
public static void printRouteArray(String[] arr)
{
int i=0;
while (i<arr.length && (arr[i]=="Up" || arr[i]=="Right"))
{
System.out.print(arr[i]+"-->");
i++;
}
System.out.println("End");
}
}
Hope you can help, thanks!
You need another 2-dimensional array inside loopAlg that memorizes which step to take to come to this next entry for every entry in your initial 2-dim array. See the following code and https://ideone.com/kM8BAZ for a demo:
public static void main(String args[])
{
String[] route = new String[100];
int[][]array = {{4,-2,3,6}
,{9,10,-4,1}
,{-1,2,1,4}
,{0,3,7,-3}};
String[] route2 = new String[100];
int max = recursionAlg(array,array.length-1,0,route);
int max2 = loopAlg(array,array.length-1,0,route2);
System.out.println("The max food in the recursion solution is: "+max);
System.out.println("and the route is: ");
printRouteArray(route);
System.out.println("The max food in the loop solution: "+max2);
System.out.println("The route is: ");
printRouteArray(route2);
}
public enum Dirs {START, FROM_LEFT, FROM_DOWN};
public static int loopAlg(int [][] arr,int x, int y, String[] route)
{
int n=0;
int[][]count = new int[arr.length][arr[0].length];
Dirs[][] directions = new Dirs[arr.length][arr[0].length];
List<String> path = new ArrayList<String>();
for(int i = x; i>=0 ; i--)
{
for(int j = 0; j<arr[0].length; j++)
{
if (i==x && j==0) {count[i][j]=arr[i][j]; directions[i][j] = Dirs.START;}
else if (i == x) { count[i][j]=count[i][j-1]+arr[i][j]; directions[i][j] = Dirs.FROM_LEFT;}
else if (j == 0) { count[i][j]=count[i+1][j]+arr[i][j]; directions[i][j] = Dirs.FROM_DOWN;}
else{
if (count[i][j-1]>count[i+1][j]) {count[i][j]=count[i][j-1]+arr[i][j];directions[i][j] = Dirs.FROM_LEFT;}
else { count[i][j]= count[i+1][j]+arr[i][j];directions[i][j] = Dirs.FROM_DOWN;}
}
}
}
int i=0, j=arr[0].length-1;
while(directions[i][j]!= Dirs.START) {
if(directions[i][j] == Dirs.FROM_LEFT) {
path.add("Right");
j--;
}
else {
path.add("Up");
i++;
}
}
Collections.reverse(path);
i=0;
for(String part:path) {
route[i] = part;
i++;
}
return count[0][arr[0].length-1];
}
I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.
import java.io.*;
public class NewClass{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int maxCounter= 0;
int input;
int lowerBound;
int upperBound;
int counter;
int numberOfCycles;
int maxCycles= 0;
int lowerInt;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String line = consoleInput.readLine();
String [] splitted = line.split(" ");
lowerBound = Integer.parseInt(splitted[0]);
upperBound = Integer.parseInt(splitted[1]);
int [] recentlyused = new int[1000001];
if (lowerBound > upperBound )
{
int h = upperBound;
upperBound = lowerBound;
lowerBound = h;
}
lowerInt = lowerBound;
while (lowerBound <= upperBound)
{
counter = lowerBound;
numberOfCycles = 0;
if (recentlyused[counter] == 0)
{
while ( counter != 1 )
{
if (recentlyused[counter] != 0)
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
else
{
if (counter % 2 == 0)
{
counter = counter /2;
}
else
{
counter = 3*counter + 1;
}
numberOfCycles++;
}
}
}
else
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
recentlyused[lowerBound] = numberOfCycles;
if (numberOfCycles > maxCycles)
{
maxCycles = numberOfCycles;
}
lowerBound++;
}
System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));
}
}
Are you making sure to accept the entire input? It looks like your program terminates after reading only one line, and then processing one line. You need to be able to accept the entire sample input at once.
I faced the same problem. The following changes worked for me:
Changed the class name to Main.
Removed the public modifier from the class name.
The following code gave a compilation error:
public class Optimal_Parking_11364 {
public static void main(String[] args) {
...
}
}
Whereas after the changes, the following code was accepted:
class Main {
public static void main(String[] args) {
...
}
}
This was a very very simple program. Hopefully, the same trick will also work for more complex programs.
If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).
The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.
Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).
Did you make sure that the output was in the same order specified in the input. I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.
ex.
Input
10 1
Output
10 1 20
If possible Please use this Java specification : to read input lines
http://online-judge.uva.es/problemset/data/p100.java.html
I think the most important thing in UVA judge is 1) Get the output Exactly same , No Extra Lines at the end or anywhere . 2) I am assuming , Never throw exception just return or break with No output for Outside boundary parameters.
3)Output is case sensitive 4)Output Parameters should Maintain Space as shown in problem
One possible solution based on above patterns is here
https://gist.github.com/4676999
/*
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
Home>Online Judge > submission Specifications
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html
Runtime : 1.068
*/
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
StringTokenizer idata;
int a, b,max;
while ((input = Main.ReadLn (255)) != null)
{
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
if (a<b){
max=work(a,b);
}else{
max=work(b,a);
}
System.out.println (a + " " + b + " " +max);
}
}
int work( int a , int b){
int max=0;
for ( int i=a;i<=b;i++){
int temp=process(i);
if (temp>max) max=temp;
}
return max;
}
int process (long n){
int count=1;
while(n!=1){
count++;
if (n%2==1){
n=n*3+1;
}else{
n=n>>1;
}
}
return count;
}
}
Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:
10 1
You should print
10 1 20
package pandarium.java.preparing2topcoder;/*
* Main.java
* java program model for www.programming-challenges.com
*/
import java.io.*;
import java.util.*;
class Main implements Runnable{
static String ReadLn(int maxLg){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
private String input;
private StringTokenizer idata;
private List<Integer> maxes;
public void run(){
String input;
StringTokenizer idata;
int a, b,max=Integer.MIN_VALUE;
while ((input = Main.ReadLn (255)) != null)
{
max=Integer.MIN_VALUE;
maxes=new ArrayList<Integer>();
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
System.out.println(a + " " + b + " "+max);
}
}
private static int getCyclesCount(long counter){
int cyclesCount=0;
while (counter!=1)
{
if(counter%2==0)
counter=counter>>1;
else
counter=counter*3+1;
cyclesCount++;
}
cyclesCount++;
return cyclesCount;
}
// You can insert more classes here if you want.
}
This solution gets accepted within 0.5s. I had to remove the package modifier.
import java.util.*;
public class Main {
static Map<Integer, Integer> map = new HashMap<>();
private static int f(int N) {
if (N == 1) {
return 1;
}
if (map.containsKey(N)) {
return map.get(N);
}
if (N % 2 == 0) {
N >>= 1;
map.put(N, f(N));
return 1 + map.get(N);
} else {
N = 3*N + 1;
map.put(N, f(N) );
return 1 + map.get(N);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNextLine()) {
int i = scanner.nextInt();
int j = scanner.nextInt();
int maxx = 0;
if (i <= j) {
for(int m = i; m <= j; m++) {
maxx = Math.max(Main.f(m), maxx);
}
} else {
for(int m = j; m <= i; m++) {
maxx = Math.max(Main.f(m), maxx);
}
}
System.out.println(i + " " + j + " " + maxx);
}
System.exit(0);
} catch (Exception e) {
}
}
}