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);
}
}
Related
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.
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..
I am trying to create a method that counts the number of times a specified character appears in a given string, by printing the sentence and the specified character and its count.
This is what I have completed so far:-
import java.util.Scanner;
public class Program4 {
public int count ( String sentence, char letter)
{
int times = 0;
for (int x=0;x<sentence.length();x++)
{
if (sentence.charAt(x) ==letter){times++;}
}
return times;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Program4 program4 = new Program4();
}
program4.count("Hello World",'o');
scan.close();
}
}
I understand I need a "system.output.println" but I don't know what value goes inside to get the output I am looking for. I would appreciate any help, I am beginner with java. Thank you.
it works, you had compile time error in code
import java.util.Scanner;
public class Program4 {
public int count(String sentence, char letter) {
int times = 0;
for (int x = 0; x < sentence.length(); x++) {
if (sentence.charAt(x) == letter) {
times++;
}
}
return times;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Program4 program4 = new Program4();
int timesCount = program4.count("Hello World", 'o');
System.out.println("count is :" + timesCount);
scan.close();
}
}
I am getting an error on the 11th line of this code "e.results();"
Here is my driver class
import java.util.Scanner;
import java.io.*;
public class LineScrabbleDriver {
public static void main(String args[]) throws IOException {
String fileName;
Scanner nameReader = new Scanner(System.in);
System.out.println("Enter a file name");
fileName = nameReader.nextLine();
Echo e = new Echo(fileName);
e.readLines();
e.results();
}
}
This is the extended class of Echo
import java.io.*;
public class LineScrabble extends Echo{
double max = 0.0;
String bestWord = "";
int lineNumer = 0;
public LineScrabble(String f) throws IOException {
super(f);
}
//scrabbles
int[] scrabbles = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
//process the given line
public void processLine(String s) {
s.toLowerCase();
int score = 0;
for(int i = 0; i<s.length(); i++){
char ch = s.charAt(i);
if(Character.isLetter(ch)){
int pos = ch - 'a';
score += scrabbles[pos];
}
}
if(score > max){
max = score;
bestWord = s;
}
}
//displays the winner and score
public void results() {
System.out.println("Winner: " + bestWord);
System.out.println("score: " + max/bestWord.length());
}
}
Here is the Echo class
import java.util.Scanner;
import java.io.*;
public class Echo{
String fileName; // external file name
Scanner scan; // Scanner object for reading from external file
public Echo(String f) throws IOException
{
fileName = f;
scan = new Scanner(new FileReader(fileName));
}
public void readLines(){ // reads lines, hands each to processLine
while(scan.hasNext()){
processLine(scan.nextLine());
}
scan.close();
}
public void processLine(String line){ // does the real processing work
System.out.println(line);
}
}
I'm not quite sure why it is giving me a undefined type error. I'm new to java programming. please help!
Because you are using the original Echo and not a LineScrabble, I think you wanted something like -
// Echo e = new Echo(fileName); //
LineScrabble e = new LineScrabble(fileName);
e.readLines();
e.results(); // <-- Echo does not have results() you could add it there, or
// use LineScrabble.