I'm doing this question on hackerrank: https://www.hackerrank.com/challenges/ctci-bubble-sort/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting
I wrote the solution in intellij, and it gives me the correct output there, but when I copied it over to the hackerrank ide, it gave me an error.
This is the code I'm talking about:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Results {
/*
* Complete the 'countSwaps' function below.
*
* The function accepts INTEGER_ARRAY a as parameter.
*/
public static void countSwaps(List<Integer> a) {
int count = 0;
boolean flag = false;
while (!flag) {
flag = true;
for (int i = 0; i < a.size() - 1; i++) {
if (a.get(i) > a.get(i + 1)) {
int temp = a.get(i);
a.set(i, a.get(i + 1));
a.set(i + 1, temp);
flag = false;
count++;
}
}
}
System.out.println(String.format(
"Array is sorted in %d swaps.%n" +
"First Element: %d%n" +
"Last Element: %d%n",
count,
a.get(0),
a.get(a.size() - 1)));
}
public static class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> a = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
Results.countSwaps(a);
bufferedReader.close();
}
}
}
This is the error: could not find or load main class solution.
Do you have any idea why I'm getting this error here? How could I fix it.
You have put the Solution class within your Result class. HackerRank wants you to put the Solution class as its own class, like this:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Results {
/*
* Complete the 'countSwaps' function below.
*
* The function accepts INTEGER_ARRAY a as parameter.
*/
public static void countSwaps(List<Integer> a) {
int count = 0;
boolean flag = false;
while (!flag) {
flag = true;
for (int i = 0; i < a.size() - 1; i++) {
if (a.get(i) > a.get(i + 1)) {
int temp = a.get(i);
a.set(i, a.get(i + 1));
a.set(i + 1, temp);
flag = false;
count++;
}
}
}
System.out.println(String.format(
"Array is sorted in %d swaps.%n" +
"First Element: %d%n" +
"Last Element: %d%n",
count,
a.get(0),
a.get(a.size() - 1)));
}
}
class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> a = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
Results.countSwaps(a);
bufferedReader.close();
}
}
Please, check your code syntax and read the error that the IDE gives you. It did explicitly tell you that Error: Could not find or load main class Solution and just a quick check on the automatic indentation would have shown you the issue.
Online Coding contest platforms generally require you to adhere to certain rules for submissions.
See: Sample Problem Statement
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
public class Solution
{
/*
* Complete the 'countSwaps' function below.
*
* The function accepts INTEGER_ARRAY a as parameter.
*/
public static void countSwaps (List < Integer > a)
{
int count = 0;
boolean flag = false;
while (!flag)
{
flag = true;
for (int i = 0; i < a.size () - 1; i++)
{
if (a.get (i) > a.get (i + 1))
{
int temp = a.get (i);
a.set (i, a.get (i + 1));
a.set (i + 1, temp);
flag = false;
count++;
}
}
}
System.out.println (String.format ("Array is sorted in %d swaps.%n" +
"First Element: %d%n" +
"Last Element: %d%n",
count,
a.get (0), a.get (a.size () - 1)));
}
public static void main (String[]args) throws IOException
{
BufferedReader bufferedReader =
new BufferedReader (new InputStreamReader (System.in));
int n = Integer.parseInt (bufferedReader.readLine ().trim ());
List < Integer > a =
Stream.of (bufferedReader.readLine ().replaceAll ("\\s+$",
"").split (" ")).
map (Integer::parseInt).collect (toList ());
countSwaps (a);
bufferedReader.close ();
}
}
The error: could not find or load main class solution. means your main() method in the Solution class could not be accessed.
Related
Many related questions seem to point to a memory allocation or a memory leak issue, but trying some of the solutions suggested, such as running code with the -Xmx2048m flag for instance, does not resolve the issue.
This leads me to wonder if there is an issue at the code level, with some kind of infinite loop.
The first file I have is PatternMatching.java:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public static List<Integer> boyerMoore(CharSequence pattern, CharSequence text, CharacterComparator comparator) {
Map<Character, Integer> lastOccurences = buildLastTable(pattern);
List<Integer> listOfOccurrences = new ArrayList<Integer>();
int i = 0;
int m = pattern.length();
int n = text.length();
while (i < n - m + 1) {
int j = m - 1;
while ((j > -1) && (comparator.compare(text.charAt(i+j), pattern.charAt(j)) == 0)) {
j--;
}
if (j == -1) {
listOfOccurrences.add(i);
} else {
int shift = (lastOccurences.get(text.charAt(i+j)) != null) ? lastOccurences.get(text.charAt(i+j)) : -1;
if (shift < j) {
i = i + j - shift;
} else {
i++;
}
}
}
return listOfOccurrences;
}
public static Map<Character, Integer> buildLastTable(CharSequence pattern) {
// WRITE YOUR CODE HERE (DO NOT MODIFY METHOD HEADER)!
int m = pattern.length();
Map<Character, Integer> lastOccurences = new HashMap<Character, Integer>();
for (int i = 0; i < m; i++) {
lastOccurences.put(pattern.charAt(i), i);
}
return lastOccurences;
}
}
And then I try to run it with the following Driver.java driver file:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Comparator;
public class Driver {
public static void main(String[] args) {
CharSequence pattern1 = "abacab";
CharSequence text1 = "abacbabadcabacab";
System.out.println(PatternMatching.boyerMoore(pattern1, text1, new CharacterComparator()));
}
}
Here is the error I get when I run the driver with the java -Xmx2048m Driver command:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.Arrays.copyOf(Arrays.java:3512)
at java.base/java.util.Arrays.copyOf(Arrays.java:3481)
at java.base/java.util.ArrayList.grow(ArrayList.java:237)
at java.base/java.util.ArrayList.grow(ArrayList.java:244)
at java.base/java.util.ArrayList.add(ArrayList.java:454)
at java.base/java.util.ArrayList.add(ArrayList.java:467)
at PatternMatching.boyerMoore(PatternMatching.java:40)
at Driver.main(Driver.java:12)
Any guidance on how to figure out what is happening would be greatly appreciated.
I am solving Beautiful Binary String problem in hackerrank but getting error may be my logic is not correct below is problem
Question
below is my logic which is checking three if conditions for the given binary string '010'.It contains minimumSteps variable which is counting the number of '010'
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the beautifulBinaryString function below.
// static String b;
static int beautifulBinaryString(String b) {
int minimumSteps=0;
for(int i=0;i<b.length();)
{
if(b.charAt(i)=='0' && b.charAt(i+1)=='1' && b.charAt(i+2)=='0')
{
minimumSteps++;
if((i+3)<b.length())
{
i=i+3;
}
}
else
{
break;
}
}
return minimumSteps;
}
// static boolean containChar(int i)
// {
// if(b.charAt(i)=='')
// {
// }
// }
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
String b = scanner.nextLine();
int result = beautifulBinaryString(b);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
Java 8
Initial Thoughts: We could use a greedy approach and starting from the left everytime we see a 010 replace the last 0 with a 1 and
continue
Examples:
01010
01110 -> 1
0100101010
0110101010
0110111010
0110111011 -> 3
java 1.8
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
input.nextLine();
String s = input.nextLine();
int count= 0;
for(int i = 0; i < s.length()-2; i++)
{
if(s.charAt(i) == '0' && s.charAt(i+1) == '1' && s.charAt(i+2) == '0')
{
count++;
i += 2;
}
}
System.out.println(count);
}
}
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
long n,a;
boolean b;
try{
Scanner sc = new Scanner(System.in);
n = sc.nextLong();
for ( long i = 0; i<n; i++){
a = sc.nextLong();
for ( long j = (a+1); j<1000000000; j++){
b = isPalindrome(j);
if ( b == true){
System.out.println(j);
break;
}
}
}
} catch ( Exception e){
return;
}
}
public static boolean isPalindrome(long n){
String intStr = String.valueOf(n);
return intStr.equals(new StringBuilder(intStr).reverse().toString());
}
}
Whats wrong with my Palindrome code?
In SPOJ, the first two test cases are compiling but for the next one and onwards it's showing the wrong answer.
First test case:
2
808
2133
output:
818
2222
The reason is that neither int neither long are big enough to store a given positive integer K of not more than 1000000 digits - 1000000 digits is well 101000000, while Long.MAX_VALUE is only 263-1.
Thus you have to use BigInteger.
The following code seems to work (no more NZEC), but it ends up with time limit exceeded.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
class Main {
public static void main(String[] args) throws java.lang.Exception {
int n = Integer.parseInt(readLine());
for (int i = 0; i < n; i++) {
BigInteger a = new BigInteger(readLine()).add(BigInteger.ONE);
if (a.signum() == -1) {
a = BigInteger.ZERO;
}
while (a.toString().length() <= 1000000) {
if (isPalindrome(a.toString())) {
System.out.println(a);
break;
}
a = a.add(BigInteger.ONE);
}
}
}
private static boolean isPalindrome(String intStr) {
int l = intStr.length();
for (int i=0, j=l-1; i < l/2+1; i++, j--) {
if (intStr.charAt(i) != intStr.charAt(j)) {
return false;
}
}
return true;
}
private static String readLine() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
}
Although I tried to solve the exception using break it still fails on the input "321". Code for bubble sort on hackerrank.
The error occurs on if(a[i+1]==n).
import java.io.*;``
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
// Write Your Code Here
int numSwaps=0;
for(int i=0;i<n;i++){
if(a[i+1]==n){ // error occurs here
break;
}
else{
if(a[i]>a[i+1]){
int temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
numSwaps++;
}
}
}
//firstElement=a[0];
//lastElement=a[n-1];
System.out.println("Array is sorted in"+" "+numSwaps+" "+"swaps."+"\n"+"First Element:"+" "+a[0]+"\n"+"Last Element:"+" "+a[n-1]);
}
}
Your condition i<n will overflow when i=n-1, because you are adding i+1, you are referencing the array out-of-bounds.
The fix is easy, however, change the condition to i<n-1.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
// Write Your Code Here
int numSwaps=0;
for(int i=0;i<n-1;i++){
if(a[i+1]==n){
break;
} else if(a[i]>a[i+1]){
int temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
numSwaps++;
}
}
//firstElement=a[0];
//lastElement=a[n-1];
System.out.println("Array is sorted in"+" "+numSwaps+" "+"swaps."+"\n"+"First Element:"+" "+a[0]+"\n"+"Last Element:"+" "+a[n-1]);
}
Also, take bit of pride in code style; I did a couple touch-ups, but its far from clean.
Just change the condition in the for loop to I < n- 1, it occurs due to the I+1 in the swapping module in your Program..
for(String temp : uniqueSet) {
if((Collections.frequency(list, temp)) >= 2) {
System.out.println(temp + "=" + (Collections.frequency(list, temp) -1));
}
}
I just want to add my repeated words count.But i cant find it.
In my code snippet,I want to get the frequently occurred words from an text file.
The problem is i can get the values of repeated words like ram=4 sam = 4 man =2,From the text file.
Now,
I want to add 4+4+2 and get total repeated word count as 10.
Any suggestions Welcomed.
I am a beginner to java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FileUtils;
public class testsrepeatedwords {
public static void main(String[] args) throws FileNotFoundException, IOException {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder\\");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
} catch (FileNotFoundException e) { e.printStackTrace(); }
String message = org.apache.commons.io.IOUtils.toString(ins);
String[] stringarray = message.split(" ");
List<String> list = new ArrayList<String>(Arrays.asList(stringarray));
list.removeAll(Arrays.asList("", null));
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet) {
if ( (Collections.frequency(list, temp) ) >= 2 ){
System.out.println(temp+"="+(Collections.frequency(list, temp) -1) ); //after subtraction
int oc = (Collections.frequency(list, temp) -1) ;
// System.out.println(oc);
// System.out.print(oc+" ");
}
}
}}}
This is my full code. :)
is 'uniqueSet' is really a Set? In set elements appeared only once. You should check your uniqueSet implementation first. If this is really a Set then Collections.frequency(list, temp)) >= 2 is always false.
Why not use a map to store the current count? Something like this:
public static void getRepeatCount(String[] c) {
HashMap<String, Integer> wordCount = new HashMap<>();
for(String currStr : c) {
if(wordCount.containsKey(currStr)) {
wordCount.put(currStr, wordCount.get(currStr) + 1);
} else {
wordCount.put(currStr,1);
}
}
int repeatedWords = 0;
for (String currKey : wordCount.keySet()) {
int currRepeatCount = wordCount.get(currKey);
repeatedWords += currRepeatCount;
System.out.println(currKey+" => "+currRepeatCount);
}
System.out.println("Total reapeated words: "+repeatedWords);
}
Test:
public static void main(String[] args) {
String[] ar = {"abc","abc","aa","aa","b"};
getRepeatCount(ar);
}
Output:
aa => 2
b => 1
abc => 2
Total reapeated words: 5
Java 8's streaming API provides a pretty elegant way of doing this. You could stream the list of words, collect it to a frequency map and then stream that map's values and reduce them to a sum:
int countThreshold = 2;
long sum =
words.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()))
.values()
.stream()
.filter(x -> x >= countThreshold)
.reduce(0L, Long::sum);