Code submission on Spoj is giving runtime error (NZEC) - java

I am struggling with Runtime Error (NZEC) on Spoj for problem,
http://www.spoj.com/problems/NHAY/
I tried so many cases from my side and everytime it is giving correct output in eclipse but could not able to find out the reason of Runtime error while submitting this on Spoj, Can anyone please help me to resolve this error.
Here is my code,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
class KMP {
public int[] lps(String needle, int needleLength)
{
int lps[] = new int[needleLength];
int j=0,i=1;
lps[0]=0;
while(i<needle.length())
{
if(needle.charAt(j) == needle.charAt(i))
{
lps[i] = j+1;
i++;
j++;
}
else
{
if(j != 0)
{
j = lps[j-1];
}
lps[i] = 0;
i++;
}
}
return lps;
}
public List<Integer> KMPalgo(String hayStack, String needle, int needleLengh)
{
int lps[] = lps(needle, needleLengh);
int i=0;
int j=0;
List<Integer> position = new ArrayList<Integer>();
while(i<hayStack.length())
{
if(hayStack.charAt(i) == needle.charAt(j))
{
i++;
j++;
}
else
{
if(j !=0)
{
j = lps[j-1];
}
else
i++;
}
if(needle.length() == j)
{
position.add(i-j);
if(j !=0)
j = lps[j-1];
}
}
return position;
}
public static void main(String[] args) throws NumberFormatException, IOException {
KMP o = new KMP();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String needlLength = bf.readLine().trim();
if(needlLength == null || needlLength.equals(""))
break;
int lNeedle = Integer.parseInt(needlLength);
String needle = bf.readLine().trim();
String haystack = bf.readLine().trim();
List<Integer> result= o.KMPalgo(haystack, needle, lNeedle);
System.out.println();
for(Integer itr : result)
System.out.println(itr);
}
}
}

The cause of the runtime error is:
String needlLength = bf.readLine().trim();
if(needlLength == null || needlLength.equals(""))
break;
You are calling trim() before checking needlLength for null.
But it seems you have at least one other error. You should replace
if(j != 0)
{
j = lps[j-1];
}
lps[i] = 0;
i++;
with
if(j != 0)
{
j = lps[j-1];
}
else
{
lps[i] = 0;
i++;
}
because now you are doing at most one jump when computing a prefix function, and that is not correct.

Related

N times problem while iterating through loop in Duplicate element program

import java.util.*;
public class TestClass {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String[] val = new String[n];
scan.nextLine();
for (int i = 0; i < n; i++) {
val[i] = scan.nextLine();
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (val[i].equals(val[j])) {
System.out.println(val[i]);
}
}
}
}
}
This is a simple code for finding duplicate array value but I need an else part where it should print "No duplicate found" but the problem is as I am iterating it through a loop it's printing N times the output.
INPUT
cat
dog
frog
owl
OUTPUT
No duplicate found
you can have a check variable for example
boolean duplicatefound = false;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (val[i].equals(val[j]))
{
System.out.println(val[i]);
duplicatefound = true;
}
}
}
if(duplicatefound)
{
System.out.println("duplicate found");
}else
{
System.out.println("No Duplicated found");
}
Can we use something like this
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
public class TestClass
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String[] val = new String[n];
scan.nextLine();
for (int i = 0; i < n; i++)
{
val[i] = scan.nextLine();
}
boolean dups = false;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (val[i].equals(val[j]))
{
System.out.println(val[i]);
} else
{
dups = true;
}
}
}
if (dups)
{
System.out.println("no duplicate found");
}
if (findDups(val))
{
System.out.println("no duplicate found");
}
if (findDups(Arrays.asList(val)))
{
System.out.println("no duplicate found");
}
}
// different approach to avoid nested loops
public static boolean findDups(String[] arr)
{
Set<String> set = new HashSet<>();
for (String i : arr)
{
if (set.contains(i))
{
return false;
} else
{
set.add(i);
}
}
return true;
}
// Java 8 streams
public static boolean findDups(List<String> list)
{
return list.stream().filter(i -> Collections.frequency(list, i) > 1)
.collect(Collectors.toSet()).isEmpty();
}
}

PALIN- The next Palindrome - a SPOJ problem

I have opened an account for Ridit, one of 7-years-old students learning Java at SPOJ. The first task i gave to him was PALIN -The Next Palindrome. Here is the link to this problem- PALIN- The next Palindrome- SPOJAfter i explained it to him, he was able to solve it mostly except removing the leading zeros, which i did. Following is his solution of the problem -
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
String[] numbersInString = new String[t];
for (int i = 0; i <t; i++) {
String str = in.nextLine();
numbersInString[i] = removeLeadingZeros(str);
}
for (int i = 0 ; i<t; i++) {
int K = Integer.parseInt(numbersInString[i]);
int answer = findTheNextPalindrome(K);
System.out.println(answer);
}
}catch(Exception e) {
return;
}
}
static boolean isPalindrome(int x) {
String str = Integer.toString(x);
int length = str.length();
StringBuffer strBuff = new StringBuffer();
for(int i = length - 1;i>=0;i--) {
char ch = str.charAt(i);
strBuff.append(ch);
}
String str1 = strBuff.toString();
if(str.equals(str1)) {
return true;
}
return false;
}
static int findTheNextPalindrome(int K) {
for(int i = K+1;i<9999999; i++) {
if(isPalindrome(i) == true) {
return i;
}
}
return -1;
}
static String removeLeadingZeros(String str) {
String retString = str;
if(str.charAt(0) != '0') {
return retString;
}
return removeLeadingZeros(str.substring(1));
}
}
It is giving correct answer in Eclipse on his computer, but it is failing in SPOJ. If someone helps this little boy in his first submission, it will definitely make him very happy. I couldn't find any problem with this solution... Thank you in advance...
This might be helpful
import java.io.IOException;
import java.util.Scanner;
public class ThenNextPallindrom2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = 0;
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()) {
t = sc.nextInt();
}
sc.nextLine();
int[] arr, arr2;
while(t > 0) {
t--;
String s = sc.nextLine();
arr = getStringToNumArray(s);
if(all9(arr)) {
arr2 = new int[arr.length + 1];
arr2[0] = 1;
for(int i=0;i<arr.length;i++) {
arr2[i+1] = 0;
}
arr2[arr2.length -1] = 1;
arr = arr2;
} else{
int mid = arr.length/ 2;
int left = mid-1;
int right = arr.length % 2 == 1 ? mid + 1 : mid;
boolean left_small = false;
while(left >= 0 && arr[left] == arr[right]) {
left--;
right++;
}
if(left < 0 || arr[left] < arr[right]) left_small = true;
if(!left_small) {
while(left >= 0) {
arr[right++] = arr[left--];
}
} else {
mid = arr.length/ 2;
left = mid-1;
int carry = 1;
if(arr.length % 2 == 0) {
right = mid;
} else {
arr[mid] += carry;
carry = arr[mid]/10;
arr[mid] %= 10;
right = mid + 1;
}
while(left >= 0) {
arr[left] += carry;
carry = arr[left] / 10;
arr[left] %= 10;
arr[right++] = arr[left--];
}
}
}
printArray(arr);
}
}
public static boolean all9(int[] arr) {
for(int i=0;i<arr.length;i++) {
if(arr[i] != 9)return false;
}
return true;
}
public static void printArray(int[] arr) {
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]);
}
System.out.println();
}
public static int[] getStringToNumArray(String s) {
int[] arr = new int[s.length()];
for(int i=0; i<s.length();i++) {
arr[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
}
return arr;
}
}

return issues in java

So I'm writing a mersense script for codeeval in java to get some practice with the language (I'm fairly new to it). At one point I'm checking if the number is prime and in my method I do the normal checks and everything looks great
public static boolean isPrime (int testValue){
if (testValue < 4){
return true;
} else if (testValue % 2 == 0){
return false;
} else {
for (int I = 1; I < Math.sqrt (testValue); I++){
if (testValue % I == 0 ){
return false;
}
}
return true;
}
}
however the only things getting through seem to be 1 and 3. Can I not do that return after the for loop is that what's wrong? Any ideas?
Edit:
Here is the full code:
import java.io.*;
import java.lang.Math;
public class Main{
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
int n;
StringBuilder result = new StringBuilder();
int candidate;
while((line = buffer.readLine()) != null){
n = Integer.parseInt(line.trim());
for(int i = 1; i < n; i++){
candidate = mersenne(i);
if(isPrime(candidate)){
System.out.println(candidate + " "+ isPrime(candidate));
if((i+1) >= n){
result.append(candidate);
}else{
result.append(candidate + ", ");
}
}
}
System.out.println(result.toString());
result = new StringBuilder();
}
}
public static int mersenne (int testValue){
return (int)Math.pow(2,testValue) - 1;
}
public static boolean isPrime(int testValue){
if(testValue < 4 && testValue > 1){
return true;
}else if(testValue % 2 == 0){
return false;
}else{
for(int i = 3; i <= Math.sqrt(testValue); i++){
if(testValue % i == 0){
return false;
}
}
return true;
}
}
}
You're starting the loop at 1. Everything % 1 is 0. Start at 3.
your code in the else block:
for (int I = 1; I < Math.sqrt (testValue); I++){
if (testValue % I == 0 ){
return false;
}
}
you should start with I=3:
for (int I = 3; I < Math.sqrt (testValue); I++)
Since every number % 1 equals to 0 so false will be returned.

Maze solver cannot find exit

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class Maze
{
private int[][] maze;
private boolean exitFound;
public Maze()
{
exitFound = false;
maze = new int[0][0];
}
public Maze(int size, String line)
{
exitFound=false;
maze = new int[size][size];
int spot=0;
for(int r= 0; r<maze.length; r++)
{
for(int c =0; c<maze[r].length; c++)
{
maze[r][c]=(line.charAt(spot*2)-48);
spot++;
}
}
}
public void checkForExitPath(int r, int c)
{
if (r >= 0 && r <maze.length &&c >= 0 && c < maze[0].length && maze[r][c] == 1)
{
checkForExitPath(r + 1, c);
checkForExitPath(r - 1, c);
checkForExitPath(r, c + 1);
checkForExitPath(r, c - 1);
maze[r][c] = 7;
if (r == maze.length-1 && c == maze[0].length-1){
this.exitFound =true;
}
}
}
public String toString()
{
String hol = "";
for(int i = 0; i<maze.length; i++){
for(int j = 0; j<maze[0].length; j++){
hol += " ";
if(maze[i][j] == 7){
hol += "1";
}
else
{
hol += maze[i][j];
}
}
hol += "\n";
}
if(this.exitFound)
{
hol+= "exit found";
}
else {
hol += "exit not found";
}
return hol;
}
}
That is my maze class the method checkForExitPath is not working or at least I think because everytime I run the maze solver with this runner class
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class MazeRunner
{
public static void main( ) throws IOException
{
Scanner file = new Scanner(new File("maze.dat"));
while(file.hasNext())
{
int size = file.nextInt();
file.nextLine();
Maze test = new Maze(size, file.nextLine());
test.checkForExitPath(0,0);
out.println(test);
}
}
}
The only output I get is that an exit is not found, but I can find an exit.
I am doing this recursively.
Your whole method does not really work recursively. If the upper left corner has a 1 which I interpret from your code as walkable way, it is changed to 7 and your method ends without recursion.
I think the four recursive method calls should be part of the first if block and no else block is necessary.

remove duplicate characters from a string

import java.util.Scanner;
public class StringWithoutDuplicate {
public static void stringWithoutDuplicate(String s1)
{
int n = s1.length();
int i = 0;
while(i<n)
{
if(s1.charAt(i) == s1.charAt(i+1))
{
if(s1.charAt(i) == s1.charAt(n-1))
{
System.out.println(s1.charAt(i));
}
i++;
}
else if(s1.charAt(i) != s1.charAt(i+1))
{
if(s1.charAt(i) == s1.charAt(n-1))
{
System.out.println(s1.charAt(i));
}
System.out.println(s1.charAt(i));;
i++;
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
s.useDelimiter(",");
String s1 = s.next();
System.out.println(s1);
stringWithoutDuplicate(s1);
}
}
The code is giving the output but with an exception
please tell me the error in my code and ways to correct it.
I don't want to change the logic of my code so kindly solve it using this logic only.
ERROR:
Range of your i is from 0 to (n-1) which is same as the range of index of characters in your string s1. This is correct.
But during the last iteration of your while loop, i = n-1
At this point, s1.charAt(i+1) becomes same as s1.charAt(n). This should be giving an error.
public static void stringWithoutDuplicate(String s1) {
int prev = -1;
for (int i = 0, size = s1.length(); i < size; ++i) {
char c = s1.charAt(i);
if (c != prev) {
System.out.println(c);
prev = c;
}
}
}

Categories

Resources