Unable to identify nzec error in code - java

I was challenged with the following question from a coding site :
==================================================================================
Given K prime numbers and T queries of form Ai, Bi, for each query print the number of integers between Ai and Bi (both inclusive) that are divisible by atleast one of the K given primes.
Input
First line: K and T.
Second line: K primes.
Next T lines, each contain Ai, Bi.
Output
Print T lines, denoting the answer to each of the T queries.
Constraints
1 ≤ K ≤ 10
1 ≤ T ≤ 100
1 ≤ A ≤ B ≤ 109
Each prime ≤ 107
Sample Input (Plaintext Link)
2 1
2 3
1 10
Sample Output (Plaintext Link)
7
Explanation
2,3,4,6,8,9,10 are the 7 numbers.
=======================================================================
When I run the following code (in system compiler) it works well, but when I submitted it to the site, all test cases throw nzec runtime error. Unfortunately the site does not share test cases but they can be created using the question.
Can any one please explain why there is a nzec error? I have used java so code is throwing an exception that needs to be caught:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner scan = new Scanner(System.in);
String[] line1 = scan.nextLine().split(" ");
int fPrime,first,last,count=0,cur;boolean duplicate=false;
int K = Integer.parseInt(line1[0]);
int T = Integer.parseInt(line1[1]);
int[][] num=new int[2][T];
// int arr[];
String[] line2 = scan.nextLine().split(" ");
if(T<=100 )
{
for(int k=0;k<T;k++)
{
if(scan.hasNextLine())
{
String[] line3 = scan.nextLine().split(" ");
num[0][k] = Integer.parseInt(line3[0]);
num[1][k] = Integer.parseInt(line3[1]);
// System.out.print("num0 = " + num[0][k]);
// System.out.println("num1 = " + num[1][k]);
}
else
{
System.out.println("Lines of Ai and Bi are missing. Make sure T lines exist");
}
}
}
else
{
System.out.print("Error! T>100");
}
if(T<=100)
{
for(int l = 0; l < T; l++)
{
first = num[0][l];
last = num[1][l];
int arr[] = new int[last];
cur=0;
// System.out.println("first = " +first);
// System.out.println("last = " +last);
for(int i = first; i<=last; i++ )
{
for(int j = 0; j < K; j++)
{
fPrime = Integer.parseInt(line2[j]);
// System.out.println("fPrime = " +fPrime);
if(( fPrime<=1000000) && (first<=1000000000 && last<=1000000000)){
if(i%fPrime==0)
{
// System.out.println("Gotcha num " + i);
for(int a = 0; a < arr.length; a++)
{
if (arr[a] == i)
{
duplicate=true;
// System.out.print("arr"+a+" = " + i);
}
}
if(duplicate==true)
{
duplicate=false;
}
else
{
arr[cur++]=i;
count++;
}
}
}
else
{
System.out.println("Make Sure 1 ? A ? B ? 10^9 Each prime ? 10^7" );
}
}
}
System.out.println(count);
}
}
else System.out.println("T can not be greater than 100");
}
}

Related

Issue with detecting an empty index in a Java char array

I am currently working on a project where I am running into an issue with detecting an empty index in a char array. The issue is that it doesn't detect whether or not there is an empty index in the array. I have tried detecting different things people have said where the placeholders for an empty char but none of them seem to work.
Here are the different things I have tried:
0, '0', 'u0000', '\u0000\, and null.
public class TestArrayChecker {
public static void main(String[] args) {
char array1[] = new char[] {'F', 'P', 'S', 'R'};
char array2[] = new char[] {'S', 'P', 'O', 'R'};
char c1 = '\u0000';
char arrayOfCorrect[] = new char[array1.length];
int correct = 0;
int counter = 0;
int close = 0;
int index = 0;
for (int i = 0; i < 4; i++) {
if (getColorAt(i, array1) == getColorAt(i, array2)) {
correct++;
arrayOfCorrect[index] = getColorAt(i, array1);
index++;
}
}
for (int i = 0; i < 4; i++) {
for (int n = -i; n < 4 - i; n++) {
if(getColorAt(i, array1) == getColorAt(i + n, array2)) {
for (int f = 0; f < arrayOfCorrect.length; f++) {
System.out.println(getColorAt(f, arrayOfCorrect) + " " + f);
System.out.println(arrayOfCorrect.length);
System.out.println(getColorAt(f, arrayOfCorrect) != c1);
if (getColorAt(f, arrayOfCorrect) != c1) {
System.out.println(getColorAt(f, arrayOfCorrect) + " " + f);
System.out.println("No Void in this array");
if(getColorAt(i, array1) != getColorAt(f, arrayOfCorrect)) {
System.out.println("This number is close: " + getColorAt(f, arrayOfCorrect));
counter++;
break;
}
} else {
counter++;
System.out.println("We got here!");
}
if (counter == 4) {
close++;
}
}
}
}
}
System.out.println(arrayOfCorrect[0] + " " + arrayOfCorrect[1] + " " + arrayOfCorrect[2] + " " + arrayOfCorrect[3]);
System.out.println(correct);
System.out.println(close);
System.out.println(counter);
}
public static char getColorAt(int index, char array[]) {
// TODO: Fill-in code to return the color at a particular position
return array[index];
}
}
This is the main part of the code that is not working:
if (getColorAt(f, arrayOfCorrect) != c1) {
System.out.println(getColorAt(f, arrayOfCorrect) + " " + f);
System.out.println("No Void in this array");
if(getColorAt(i, array1) != getColorAt(f, arrayOfCorrect)) {
System.out.println("This number is close: " + getColorAt(f, arrayOfCorrect));
counter++;
break;
}
} else {
counter++;
System.out.println("We got here!");
}
Here is the output of the console, the last two numbers are supposed to print out 1 and 4.
P 0
4
true
P 0
No Void in this array
R 1
4
true
R 1
No Void in this array
This number is close: R
P 0
4
true
P 0
No Void in this array
This number is close: P
P 0
4
true
P 0
No Void in this array
This number is close: P
P R
2
0
3
I haven't removed all of my debug coding so please ignore that.
Thanks all for the help.
hmmm, okay. First of all, the issue isn't in detecting an empty char, I've tested it myself with this code :
public static void main(String[] args) {
char array[] = new char[10];
int emptyCounter = 0;
for(int i = 0; i < array.length; i++) {
if (array[i] == 0) {
emptyCounter++;
}
}
System.out.println(emptyCounter);
}
and I get an output of 10, as I left all chars empty.
Now, looking at your code, we can see why "getColorAt(f, arrayOfCorrect) != c1" will always be true : you break out of the for loop before it can encounter an empty string. You've got "arrayOfCorrect = ['P', 'R', empty, empty].
This is the part of your code that makes it so :
if(getColorAt(i, array1) != getColorAt(f, arrayOfCorrect)) {
System.out.println("This number is close: " + getColorAt(f, arrayOfCorrect));
counter++;
break;
}
As you iterate through array1 with i, the condition is true when i is equal to 0 and 2. As we can see by your results, f is never going higher than 1 but is not the source of the problem.
As we go higher to get to the source of the problem, we come across this :
for (int n = -i; n < 4 - i; n++) {
if(getColorAt(i, array1) == getColorAt(i + n, array2)) {
...
}
}
Btw, this isn't a good practice... this is like doing 2 + 10 - 10 + 2 = 4. As far as I can see, this would do the same work :
for (int n = 0; n < 4; n++) {
if(getColorAt(i, array1) == getColorAt(n, array2)) {
...
}
}
And it is now more easy to understand what you are trying to do here.
So, for every char in array1, you check every char of array2 until you find a correspondence. So basically, the condition will be true only 3 times : when array1[1] = array2[1], array1[2] = array2[0] and array1[3] = array2[3].
When i = 1, "getColorAt(i, array1) != getColorAt(f, arrayOfCorrect)" is true when f = 1 ('P' != 'R') and you exit the nested loop there.
When i = 2, "getColorAt(i, array1) != getColorAt(f, arrayOfCorrect)" is true when f = 0 ('S' != 'P') and you exit the nested loop there.
When i = 3, "getColorAt(i, array1) != getColorAt(f, arrayOfCorrect)" is true when f = 0 ('R' != 'P') and you exit the nested loop there.
So yeah, counter++ gets called only 3 times and you never encounter an empty char.
Hope this helps.

Trying to find a pattern from a vector in an array

I'm learning Java and I have this exercise where I need to find a pattern from a vector in a matrix and then copy the number of the rows where the pattern is found to another vector.
I'm trying to copy each row of the matrix to another vector and then compare it with the pattern, but it only saves the first row where the pattern is found
package exercise;
import java.io.*;
import java.util.Locale;
import java.util.Scanner;
public class Exercise {
static final int M = 7;
static final int N = 7;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Scanner fEnt = null;
Scanner fEnt1 = null;
PrintStream fSal = null;
double[] pattern = new double[M];
double[][] m = new double[N][N];
double[] aux = new double[N];
int[] res = new int[N];
int i, ax, j, vLon, k, z, w = 0;
boolean found, repeated;
System.out.print("Enter matrix filename: ");
String nomEnt = scanner.next();
System.out.print("Enter pattern filename: ");
String nomEnt1 = scanner.next();
System.out.print("Enter new filename: ");
String nomSal = scanner.next();
try {
fEnt = new Scanner(new File(nomEnt));
fEnt.useLocale(Locale.US);
fEnt1 = new Scanner(new File(nomEnt1));
fEnt1.useLocale(Locale.US);
fSal = new PrintStream(new File(nomSal));
i = 0;
ax = 0;
while (fEnt1.hasNext() && i < M) {
pattern[i] = fEnt1.nextDouble();
i++;
}
vLon = i;
j = 0;
i = 0;
while (fEnt.hasNext() && i < N) {
while (fEnt.hasNext() && j < N) {
m[i][j] = fEnt.nextDouble();
j++;
}
i++;
}
k = 0;
for (i = 0; i < N; i++) {
repeated = false;
for (j = 0; j < N; j++) {
aux[j] = m[i][j];
}
z = 0;
found = true;
while (z <= N - vLon) {
j = 0;
while (j < vLon && found) {
if (aux[z + j] != pattern[j]) {
found = false;
}
j++;
}
if (found) {
repeated = true;
}
z++;
}
if (repeated) {
res[k] = i;
k++;
}
w = k;
}
if (w == 0) {
System.out.println("The pattern wasn't found in the matrix");
} else {
for (i = 0; i < w; i++) {
fSal.print(String.valueOf(res[i]) + "\t");
}
fSal.println();
System.out.println("The vector has been saved.");
}
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
} finally {
if (fEnt != null) {
fEnt.close();
}
if (fSal != null) {
fSal.close();
}
}
}
}
For example, if it reads the matrix
5 2 1 2 3 4
5 3 5 1 2 3
1 2 5 2 4 6
6 7 3 5 1 2
1 2 3 6 8 4
4 5 3 2 4 6
Then if the pattern is 1 2 3, it should save the following vector 1 2 5
This is a question of basic debugging. Therefore, TL;DR use your IDE's debugger.
Long version:
If you have an IDE, then use its debugging features. Eclipse and IntelliJ both have great debugging support and mountains of online tutorials on how to do it.
Things I found wrong while debugging your code (not everything):
Your matrix is only reading into the first line. 2nd, 3rd, etc. rows are all 0's. Also, you are setting N and M to 7 but they should be 6.
-- hint -- step through it and watch what happens right after you increment i, on your next entry into the loop on j. Line ~58
You are doing something wrong with your 'found' flag, causing your program to quit checking after it initially fails. Line ~70
-- hint -- double-check your logic here - I don't think 'found' means what you think it means in your code

Java - vertical integers and palindrome

I stumbled upon an exercise that asked me to reproduce this (that's the expected output):
11111
3456789012109876543
This is a palindrome (at the bottom) where numbers higher that 9 (double digits) have to be written vertical. This sounds complicated to me, and I needed some help.
This is what I did so far, the palindrome:
class Print {
public static void main(String[] args) {
System.out.println("Insert a number from 1 to 100: ");
int input = Read.anInt();
System.out.println("Insert another number from 1 to 100: ");
int output = Read.anInt();
int a = input;
for (int i = a; i < output; i++){
System.out.print(a);
a++;
}
a = input -1;
for (int j = output; j > a; j--){
System.out.print(output);
output--;
}
}
}
Could you help me by explaining how to make sure numbers higher than 9 will be written vertically?
AdamRice: i mean this:
3456789111119876543
01210
But what I've managed to do so far is this mess:
456789101
0
111
1
121110987654
This is all probably because I'm completely ignoring arrays.
Apologies for being a bit slow. After finally understanding the problem, I think I have a solution.
import java.util.Scanner;
public class VerticalText {
public static void main(String[] args) {
Scanner Read = new Scanner(System.in);
System.out.println("Insert a number from 1 to 100: ");
int start = Read.nextInt();
System.out.println("Insert another number from 1 to 100: ");
int end = Read.nextInt();
String numbers = "";
for(int i = start; i <= end; i++)
{
if(i < 10)
{
numbers += String.format("%02d", i);
}
else
{
numbers += i;
}
}
for(int i = (end-1); i >= start; i--)
{
if(i < 10)
{
numbers += String.format("%02d", i);
}
else
{
numbers += i;
}
}
String row1 = "";
String row2 = "";
char[] chars = numbers.toCharArray();
for(int i = 0; i < chars.length; i++)
{
if(chars[i] == '0')
{
chars[i] = ' ';
}
row1 += chars[i];
i++;
row2 += chars[i];
}
System.out.println(row1);
System.out.println(row2);
}
}
With inputs 5 and 15, it produced the following output:
11111111111
567890123454321098765
Explanation
I build a string of the numbers and if it's less than 10 format it with a leading 0. This extra 0 is just a placeholder. When it comes to printing, we can print a space instead of a zero.

Finding Consecutive Duplicate integers in an array

I have a problem in which I need to ask for user input for how many times they wish to roll a die and to create and print that an array that has the rolls requested. So far I can create the array, however another part of the problem is that whenever there are consecutive duplicate rolls I must put parentheses around them. For example inputting 11, creates the array
{1 , 2 , 1 , 4 , 4, 6 , 2 , 3 , 5 , 5 , 5} would print 1 2 1 ( 4 4 ) 6 2 3 ( 5 5 5 )
So far I have written
import java.util.Scanner;
import java.util.Random;
public class HW0603 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many times would you like to roll: ");
System.out.println();
int x = input.nextInt();
run(rolls(x), x);
}
public static int[] rolls(int x) {
Random random = new Random();
int y[] = new int[x];
for (int i = 0; i < x; i++) {
int z = random.nextInt(6) + 1;
y[i] = z;
}
return y;
}
public static void run(int a[], int b) {
for (int i = 1; i < b; i++) {
System.out.print(a[i] + " ");
}
}
}
As for the parentheses I honestly don't know how to start. Using if statements didn't work for me, my if statement variations seem to give me out of bound errors since I compare a[i] to a[i+1] and a[i-1]. Could anyone give me a place to start or some tips to being extracting consecutive duplicates?
you need to compare current item with next item
if equal, print "(" then print the item
make flag paranOpened that you have opened (, so you don't reopen ( again, to avoid this: 1 (2(2(2..., then when curr!=next, based on that flag either print the item or print the item then close the ")"
at end of loop
print lat item (b-1) that was excluded from the loop ..;i < b - 1;.., and check if you have opened "("
your run() method will be like this
static boolean paranOpened = false;
public static void run(int a[], int b) {
for (int i = 0; i < b - 1; i++) {
if (a[i] == a[i + 1]) {
if (!paranOpened) {
paranOpened = true;
System.out.print(" (");
}
System.out.print(a[i] + " ");
} else {
System.out.print(a[i] + " ");
if (paranOpened) {
System.out.print(") ");
paranOpened = false;
}
}
}// for loop
// print last item in array #(b-1)
System.out.print(a[b - 1] + " ");
// check if opened ( , then close it
if (paranOpened) {
System.out.print(") ");
}
}// run()
this is a quick solution, there could be better algorithms
The first problem with you program is that the counter in your run method starts
from 1 which should be zero. Your current program does not print the first element of the array.
then you need to check each element with the next one to see if they are duplicate and if they are open the parenthesis and vice versa.
The last element does not need to be checked so print it outside the loop and close the parenthesis if needed.
By the way you do not need to pass the array size element with it. Just use the array.length method.
public static void run(int a[], int b)
{
boolean pOpen = false;//keep track if parenthesis is open
for (int i = 0; i<a.length; i++)
{
if (i < a.length-1)//prevent out of bound exception
{
if (a[i] == a[i+1] && !pOpen )// check if it is needed to `open or close the parenthesis`
{
System.out.print("(");
pOpen = true;
}
System.out.print(a[i] + " ");
if (a[i] != a[i+1] && pOpen)
{
System.out.print(")");
pOpen = false;
}
}
}
System.out.print(a[a.length-1]);//print the last element
if (pOpen)//close the parenthesis if open
{
System.out.print(")");
}
}
Iterate through your array and keep a boolean that marks if parenthesis have opened.
import java.util.*;
class Ideone
{
public static int[] rolls(int x) {
Random random = new Random();
int y[] = new int[x];
for (int i = 0; i < x; i++) {
int z = random.nextInt(6) + 1;
y[i] = z;
}
return y;
}
public static void run(int a[], int b) {
StringBuilder sb = new StringBuilder();
String out = "";
boolean parens = false;
for (int j = 0; j < a.length; j++)
{
out = "" + a[j]; //by default just add an element
//check for duplicate and build parenthesis
if (j + 1 < a.length && a[j] == a[j+1]) //duplicate found
{
if (!parens) // if no parenthesis
{
parens = true; //start parenthesis
out = "( " + a[j];
}
}
else
{
if (parens) //if parenthesis already started
{
out = a[j] + " )";
parens = false; //stop parenthesis
}
}
sb.append(" " + out);
}
// if the last element occured multiple times
if (parens) //should end parens
{
sb.append(a[a.length-1] + " )");
}
//print out the result
System.out.println(sb.toString());
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.print("How many times would you like to roll: ");
System.out.println();
int x = input.nextInt();
run(rolls(x), x);
}
}
You need to use boolean to check whether your parenthesis is open or no.
Here I've tried to create a clean and readable example:
Sample code:
public class HelloWorld {
public static void main(String[] args) {
int arr[] = { 1, 2, 1, 4, 4, 6, 2, 3, 5, 5, 5 };
printConsecutiveInBrace(arr);
}
public static void printConsecutiveInBrace(int arr[]) {
int printFrom = 0;
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1 || arr[i] != arr[i + 1]) {
print(arr, printFrom, i);
printFrom = i + 1;
}
}
}
public static void print(int arr[], int printFrom, int printTo) {
if (printFrom < printTo) //Here check: Consecutive Duplicate
System.out.print("( ");
for (int i = printFrom; i <= printTo; i++)
System.out.print(arr[i] + " ");
if (printFrom < printTo)
System.out.print(") ");
}
}
Output:
1 2 1 ( 4 4 ) 6 2 3 ( 5 5 5 )

Print fibonacci up to user entered number

I'm trying to print the Fibonacci series up to whatever number the user types in. The problem is that my code ends up printing that amount of numbers. If a user enters 100, I want the code to stop at 100, but my code prints 100 numbers. Also, I'm supposed to have printf and a while statement. I don't even know how to use printf.
package l12;
import java.util.Scanner;
public class L12 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter an integer: ");
int n = console.nextInt();
System.out.println("The Fibonacci numbers less than " + n + " are: ");
for(int i=1; i<=n; i++){
System.out.print(fibonacci(i) +" ");
}
}
public static int fibonacci(int n){
if(n == 1 || n == 2){
return 1;
}
int f1=1;
int f2=1;
int fibonacci=1;
for(int i= 3; i<= n; i++){
do { fibonacci = f1 + f2;
f1 = f2;
f2 = fibonacci;
}
while (fibonacci <= n);
}
return fibonacci;
}
}
A simple way of doing it would be :
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("Enter an integer: ");
int n = console.nextInt();
if(n>1) {
System.out.println("The Fibonacci numbers less than " + n + " are: ");
System.out.print("1, 1, ");
int f2=1;
int fibonacci=1;
for(int i=1; i+f2 < n;){
fibonacci = i + f2;
i = f2;
f2 = fibonacci;
System.out.print(fibonacci+", ");
}
} else {
System.out.println("There are no numbers less than " + n + " in the series");
}
}
If I understand your question, then you could change this (which stops when i > n)
for(int i=1; i<=n; i++){
System.out.print(fibonacci(i) +" ");
}
to something like this, which stops when the result of fibonacci(i) > n, stores the result in fib and uses printf (the Format String syntax says that with d The result is formatted as a decimal integer).
int fib;
for (int i = 1; (fib = fibonacci(i)) <= n; i++) { // <-- stop wehn fib >= n
System.out.printf("%d ", fib); // <-- printf.
}
System.out.println(); // <-- Add a new-line.
I will be giving you an answer in Go so if you watch closely, you'll see the following sequence:
1 1 2 3 5 8 13 21 34 55 89 144 ...
The formula for mapping the Fibonacci sequence is:
Then if you code this (Go):
package main
import "fmt"
func fibonacci() func() int {
first, second := 0, 1
return func() int {
ret := first
first, second = second, first+second
return ret
}
}
func main() {
f := fibonacci()
for i := 0; i < /* What users enter */; i++ {
fmt.Println(f())
}
}
You'll see the numbers till entered by user. I hope that approach helped you understand better the problem!
Cheers!
This prints 100 numbers because you are looping n times no matter what:
for(int i=1; i<=n; i++){
System.out.print(fibonacci(i) +" ");
}
I would recommend changing this to a do-while loop as well:
int i = 1;
int fib;
do{
fib = fibonacci(i);
System.out.print(fib + " ");
} while(fib < n);
The above code, as I hinted at, is always going to loop 100 times. Even though your fibonacci method doesn't let it exceed 100, your for loop is still going to print 100 numbers.

Categories