Which test case causes the Runtime Error? - java

This was one of coding jam 2020 questions with the link attached below (round is complete), and while I could not reproduce it, the google engine reported that this was a runtime error even for the small test case. It could pretty much handle any test case I threw at it. Perhaps I am missing an edge case, but not sure what it is.
My understanding is that this is O(N) performance. All it really does is to check if the boolean sub array is free(false) and if so, assign the task to that sub array(true) with may be 2N compares.
https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/000000000020bdf9
import java.util.*;
import java.io.*;
//Parenting Partnering Returns
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt(); // Scanner has functions to read ints, longs, strings, chars, etc.
for (int ijk = 1; ijk <= t; ++ijk) {
int N = in.nextInt();
String ans;
StringBuilder sb = new StringBuilder();
boolean[] cal = new boolean[1442];
boolean[] jal = new boolean[1442];
int si, se;
boolean canC,canJ, isPossible = true;
for (int i = 0 ; i < N ; i++) {
si = in.nextInt();
se = in.nextInt();
canC = false; canJ = false;
if (cal[si + 1] == false && cal[se] == false || cal[si] == false && cal[se -1] == false) {
for (int j = si ; j <= se; j++) cal[j] = true;
sb.append('C'); canC = true; continue;
} else if (jal[si + 1] == false && jal[se] == false || jal[si] == false && jal[se -1] == false) {
for (int k = si ; k <= se; k++) jal[k] = true;
sb.append('J'); canJ = true; continue;
} else {
isPossible = false;
break;
}
}
ans = sb.toString();
if(isPossible)
System.out.println("Case #" + ijk + ": " + ans);
else System.out.println("Case #" + ijk + ": " + "IMPOSSIBLE");
}
//in.close();
}
}

Related

can someone help me clear these errors

I am trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}
A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.

Currently compiling, but receiving nothing but end to program?

import java.util.Scanner;
public class PD {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter your number: " );
int number = input.nextInt();
for (int count = 2; count < number; count++) {
String blank = "";
String Snumber = count + blank;
if (isPalindromic(count) && isPrime(count) &&
isPalindromic((int)(Snumber.length())) &&
isPrime((int)(Snumber.length()))){
System.out.println( count + "is double palidromic prime");
}
else
continue;
}
}
// method to find palindromic
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
for (int i = 0, q = 1; i <= (convert.length()/2 - 1); i++, q++) {
if (convert.substring(i,q) == convert.substring(convert.length() - q, convert.length() - i)){
return true;
}
}
return false;
}
// method to find prime
public static boolean isPrime(int count ) {
for (int divisor = 2; divisor <= count/2; divisor++) {
if (count % divisor == 0) {
return false;
}
}
return true;
}
}
Currently the thing compiles and ask for input, but it always results in nothing.
Does someone see something wrong with my program that is obvious wrong.
Overall, the program receives input and has to look through values 2 until it hits the value the user wants and print the ones that follow the if statement.
Your isPalindromic method is not functioning properly. It is not returning true for palindromic numbers. Change it to this:
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
int n = convert.length();
for (int i = 0; i < (n / 2 + 1); i++) {
if (convert.charAt(i) != convert.charAt(n - i - 1)) {
return false;
}
}
return true;
}

Output incorrect [duplicate]

This question already has an answer here:
Output of numbers are incorrect sometimes.
(1 answer)
Closed 9 years ago.
When I do different combinations like d-c+a+b it gives me a inccorect number like 118.0. Can someone tell me where in my code my calculations are wrong..
Thank you
the ValVarPairs.txt contains these numbers-> a=100,b=5,c=10,d=13
This is what i coded.
package com.ecsgrid;
import java.io.*;
public class testC {
public static void main(String[] args) {
int i = 0,j = 0;
double result, values[] = new double[4];
char k, operators[] = new char[3];
for (i = 0; i <= 2; i++)
operators[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)){
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
}
catch(FileNotFoundException e) { System.err.println(e); return; }
catch(IOException f) { System.out.println(f); return; }
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine();
}
catch(IOException f) { System.out.println(f); return; }
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
result = values[0];
for (i = 0; i <= 2; i++){
if (operators[i] == '+')
result = result + values[i+1];
else
result = result - values[i+1];
}
System.out.println(result);
}
}
Right now you would be getting the same output if your input was -++
You never parse for the order or a, b, c and d. You always assume the order a->b->c->d.
So d-c+a+b will be: a-b+c+d which is consistent with the output you provided(100-5+10+13 = 118)
OP's CODE
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
/OP'S CODE
In this loop, when k is not an operator, you should be reading which letter it is, and store the order in which the letters appeared. Or build some other kind of mapping. In any case you can't just ignore non-operator characters because they are part of the input.
Let's debug this a little, add a few system outs...
this is what you would see for each step
100.0 - 5.0
95.0 + 10.0
105.0 + 13.0
118.0
your value array is {100,5,10,13} and your operator array is {-,+,+}
you have not mapped a = 100, b = 5, c= 10, d = 13, unless you map those then parse the operands using the mapping based on the non operand input keys, it is not going to work.
So, if I were to use the character's int values, I would be able to translate it this way.
import java.io.*;
public class TestC {
public static void main(String[] args) {
int i = 0, j = 0;
double result, values[] = new double[4];
char k, operatorsAndOperands[] = new char[3];
for (i = 0; i <= 2; i++)
operatorsAndOperands[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)) {
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
for (int l = 0; l < values.length; l++) {
System.out.println(values[l]);
}
} catch (FileNotFoundException e) {
System.err.println(e);
return;
} catch (IOException f) {
System.out.println(f);
return;
}
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine().toUpperCase();
} catch (IOException f) {
System.out.println(f);
return;
}
if(InputText.length() > 0){
operatorsAndOperands = new char[InputText.length()];
} else {
System.out.println("No Operations specified");
return;
}
for (i = 0; i < InputText.length(); i++) {
k = InputText.charAt(i);
operatorsAndOperands[j++] = k;
}
result = 0;
for (i = 0; i < operatorsAndOperands.length; i++) {
System.out.println(operatorsAndOperands[i] + " " + (int)operatorsAndOperands[i]);
if(i+1<operatorsAndOperands.length)
System.out.println(operatorsAndOperands[i+1]);
switch(operatorsAndOperands[i]){
case '+':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result+=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
case '-':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result-=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
default:
result = values[(int)operatorsAndOperands[i] - (int)'A'];
break;
};
System.out.println(result);
}
System.out.println(result);
}
}

Java for loop error

I am trying to get user input for sortValues[] array using the for statement (enter character 1, enter character 2, etc).
However, when I execute this, the program will not allow me to enter for character 2, instead skipping directly to character 3, as seen below.
How to resolve this? The code is included below.
thanks!
static public void s_1d_char () {
int counter=0;
int x=0;
c.print("How many characters? ");
counter = readInt();
char[] sortValues = new char[counter+1];
for (x=1;x<=counter;x++) {
System.out.println("Enter character "+(x)+":");
sortValues[x] = readChar();
}
}
readChar implementation (this is from a library):
public synchronized char readChar ()
{
char result, ch;
if (ungotChar != EMPTY_BUFFER)
{
result = (char) ungotChar;
ungotChar = EMPTY_BUFFER;
return (result);
}
if (lineBufferHead != lineBufferTail)
{
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
return (result);
}
startRow = currentRow;
startCol = currentCol;
if (currentRow > maxRow)
{
startRow++;
currentCol = 1;
}
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (true);
// Wait for a character to be entered
while (true)
{
ch = getChar ();
if (ch == '\n')
{
clearToEOL = false;
if (echoOn)
print ("\n");
clearToEOL = true;
lineBuffer [lineBufferHead] = '\n';
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
break;
}
if (ch == '\b')
{
if (lineBufferHead == lineBufferTail)
{
consoleCanvas.invertScreen ();
}
else
{
int chToErase;
lineBufferHead = (lineBufferHead + lineBuffer.length - 1) % lineBuffer.length;
chToErase = lineBuffer [lineBufferHead];
if (echoOn)
{
if (chToErase != '\t')
{
erasePreviousChar ();
}
else
{
int cnt;
eraseLineOfInput ();
cnt = lineBufferTail;
while (cnt != lineBufferHead)
{
print (lineBuffer [cnt]);
cnt = (cnt + 1) % lineBuffer.length;
}
}
}
}
} // if backspace
else if (ch == '\025')
{
if (echoOn)
{
eraseLineOfInput ();
}
lineBufferHead = lineBufferTail;
}
else
{
if (echoOn)
{
print (ch);
}
lineBuffer [lineBufferHead] = ch;
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
}
} // while
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (false);
return (result);
}
I recommend getting user input with a scanner:
import java.util.Scanner;
// ...
int counter = 0;
System.out.println("How many characters?");
Scanner keyboard = new Scanner(System.in);
counter = keyboard.nextInt();
char[] sortValues = new char[counter+1];
// Start your index variable off at 0
for (int x = 0; x < counter; x++) {
System.out.println("Enter character "+(x)+":");
keyboard = new Scanner(System.in);
String line = keyboard.nextLine();
sortValues[x] = line.charAt(0);
}
This will capture the first character of the line. If the user enters more than one character, the program will read only the first.
Also, you should really start your index variable x off at 0, considering arrays are 0-based indexed.
instead of readChar() try:
sortValues[x] = Integer.parseInt(System.console().readLine());
How to read integer value from the standard input in Java

Getting a NumberFormatException

I was writing some code for an interviewstreet.com challenge
My code gives a NumberFormatException
import java.io.*;
public class BlindPassenger
{
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int t,n;
//System.out.println(line);
t = Integer.parseInt(line);
for(int i=0;i<t;++i)
{
line = br.readLine();
n = Integer.parseInt(line); --n;
if(n == 0)
{
System.out.println("poor conductor");
}
else
{
char direction='l',seat_posn='l';
int row_no = 0, relative_seat_no = 0;
row_no = (int) Math.ceil(n/5.0);
relative_seat_no = n % 5;
if(row_no % 2 == 0)
{
//even row, need to reverse the relative seat no
relative_seat_no = 6 - relative_seat_no;
}
if(relative_seat_no < 3)
{
direction = 'L';
if(relative_seat_no == 1) seat_posn = 'W';
else seat_posn = 'A';
}
else
{
direction = 'R';
if(relative_seat_no == 3) seat_posn = 'A';
else if(relative_seat_no == 4) seat_posn = 'M';
else seat_posn = 'W';
}
System.out.println(row_no + " " + seat_posn + " " + direction);
}
}
}
}
Here is the test case that they use
3
1
2
3
Output:
poor conductor
1 W L
1 A L
There seems to be a trailing space or something at the end of each line that causes the exception.
$ java BlindPassenger <input00.txt
Exception in thread "main" java.lang.NumberFormatException: For input string: "3
"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at BlindPassenger.main(BlindPassenger.java:11)
This has taken up half an hour and I don't know how to fix this.
Kills the fun of the event doesn't it. Can someone tell me what I'm doing wrong.
Integer.parseInt() can't handle strings that don't fit its expected format, as you've found out. You could trim() the string before you parse it:
t = Integer.parseInt(line.trim());
This gets rid of leading and trailing whitespace.
You have to trim the string
import java.io.*;
public class BlindPassenger
{
public static boolean isEmpty(final String string)
{
return string == null || string.trim().isEmpty();
}
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int t,n=0;
//System.out.println(line);
t = Integer.parseInt(line);
for(int i=0;i<t;++i)
{
line = br.readLine();
if(!isEmpty(line)){
n = Integer.parseInt(line.trim());
--n;
}
if(n == 0)
{
System.out.println("poor conductor");
}
else
{
char direction='l',seat_posn='l';
int row_no = 0, relative_seat_no = 0;
row_no = (int) Math.ceil(n/5.0);
relative_seat_no = n % 5;
if(row_no % 2 == 0)
{
//even row, need to reverse the relative seat no
relative_seat_no = 6 - relative_seat_no;
}
if(relative_seat_no < 3)
{
direction = 'L';
if(relative_seat_no == 1) seat_posn = 'W';
else seat_posn = 'A';
}
else
{
direction = 'R';
if(relative_seat_no == 3) seat_posn = 'A';
else if(relative_seat_no == 4) seat_posn = 'M';
else seat_posn = 'W';
}
System.out.println(row_no + " " + seat_posn + " " + direction);
}
}
}
}

Categories