So I was solving this Question on HackerRank (Project Euler Q1) link here, and have used the following code to solve it
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) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int T = 0;
ArrayList<Integer> N = new ArrayList<Integer>();
String[] Input = args;
if (args.length>1){
T = Integer.parseInt(args[0]);
if(T<1||T>Math.pow(10,6))
System.exit(0);
}
if (args.length-1 == T){
for (int i=1;i<args.length;i++){
N.add(Integer.parseInt(args[i]));
int sum3=0,sum5=0,sum15=0;
int count=0;
while (count<N.get(i-1)){
sum3+=count;
count+=3;
}
count =0;
while (count<N.get(i-1)){
sum5+=count;
count+=5;
}
count =0;
while (count<N.get(i-1)){
sum15+=count;
count+=15;
}
N.set(i-1,(sum3+sum5-sum15));
}
}
for(int j=0;j<N.size();j++)
System.out.println(N.get(j));
}
}
This gives me the following output on an IDE :
23
2318
While Inputting :
2
10
100
And this matches the expected output on HackerRank, but however When I use this code on the website, It says :
Input (stdin)
2
10
100
Your Output (stdout)
~ no response on stdout ~
Expected Output
23
2318
Compiler Message
Wrong Answer
One thing I could observe was I couldn't print anything from inside a loop on HackerRank. What would the solution to this be?
You're not reading from STDIN the way HackerRank wants you to. Instead of getting your input from args, you should be doing this kind of thing:
Scanner sc = new Scanner(System.in);
int numberOfTestCases = sc.nextInt();
and so on.
I just ran this code, compiled fine and submitted it.
import java.io.*;
public class Solution{
public static void main(String[] args) throws IOException
{
//Input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int[] N = new int[T];
for(int t = 0; t < T; N[t++] = Integer.parseInt(br.readLine())){
}
br.close();
br = null;
//Solve
long[] V = new long[T];
for(int t = 0; t < T; ++t){
int n = N[t] - 1;
V[t] = 3*nSum(n/3) + 5*nSum(n/5) - 15*nSum(n/15);
}
//Print
StringBuilder sb = new StringBuilder();
for(int t = 0; t < T; sb.append(V[t++]).append("\n")){
}
System.out.print(sb);
}
public static long nSum(int n){
long v = n;
return (v*v + v) >> 1;
}
}
I had the same problem with a php code and I used return instead of echoing for your case replace sout with return
Related
Actually, I am doing an exercise from HackerEarth.
The exercise is pretty simple: I have to use a min-max algorithm but I have some struggles when I use the readLine method from the variable BufferReader.
I cannot figure out why but my min variable for an iteration keep the Integer.MAX_VALUE.
Code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int N = Integer.parseInt(br.readLine());
while (T-- >= 0) {
String[] line = br.readLine().trim().split("\\s");
int min = Integer.MAX_VALUE;
for (int i = 0; i < line.length - 1; i++) {
min = Math.min(min, Integer.parseInt(line[i]));
}
System.out.println(min);
}
}
}
Output
1
2147483647
2
I've made many corrections to your code.
You are not reading every N of every test case, you only read it once. You have to put it inside the while loop.
Method trim is unnecessary because inputs from the problems are always in the right manner.
Use > not >= when comparing using array lengths or the number of test cases, because it will iterate once more even if the index is already beyond the array's capacity or 0.
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while (T-- > 0) {
br.readLine(); // to read N
String[] line = br.readLine().split(" ");
int min = Integer.MAX_VALUE;
for (int i = 0; i < line.length; i++) {
min = Math.min(min, Integer.parseInt(line[i]));
}
System.out.println(min);
}
}
I am solving the "The Love-Letter Mystery" problem may be my logic is correct but it is showing the timings problems The Question is
Question here.My solution for same is given below. It contains two functions one is theLoveLetterMystery(String s) which is returning sum_minimum_Steps and other is conversionCount(String s,int i,int j) which is returning int characterCount variable.It sums all the minimum steps to return the value
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 theLoveLetterMystery function below.
static int theLoveLetterMystery(String s) {
int startCounter=0,endCounter=(s.length()-1),sum_minimum_Steps=0;
// s.charAt(startCounter)!=s.charAt(endCounter)
while(startCounter!=endCounter)
{
if(s.charAt(startCounter)!=s.charAt(endCounter))
{
//minimun steps function executes
sum_minimum_Steps+=conversionCount(s,startCounter,endCounter);
}else{
startCounter++;
endCounter--;
}
}
return sum_minimum_Steps;
}
static int conversionCount(String s,int i,int j) {
int charStartAscii=(int)s.charAt(i);
int charEndAscii=(int)s.charAt(j);
int characterCount=0;
while(charStartAscii!=charEndAscii)
{
charEndAscii--;
characterCount++;
}
return characterCount;
}
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 q = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int qItr = 0; qItr < q; qItr++) {
String s = scanner.nextLine();
int result = theLoveLetterMystery(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}
bufferedWriter.close();
scanner.close();
}
}
Starting from the assumption we are working on an alphabet of 26 letters(range a - z) "The Love-Letter Mystery" question is about find the minimum number of operations consisting of decrement of value 1 of a letter (for example d -> c and excluding letter a) to convert a string to a palindrome string. This can be obtained adding the absolute int differences between chars standing in positions i and n - i - 1 where n is the length of the string and iterating over half of the string. Below the code:
public static int conversionCount(String s) {
char[] arr = s.toCharArray();
int length = s.length();
int count = 0;
for (int i = 0; i < length / 2; ++i) {
count += Math.abs((int) (arr[i] - arr[length - i - 1]));
}
return count;
}
Note: I tested it in hackerrank passing all tests.
function theLoveLetterMystery($s) {
$s = strtoupper($s);
$alpha = array('A','B','C','D','E','F','G','H','I','J','K', 'L','M','N','O','P','Q','R','S','T','U','V','W','X ','Y','Z');
$alpha_flip = array_flip($alpha);
// Write your code here
$i = 0;
$j = strlen($s)-1;
$sol = 0;
while($i<$j){
$sol += abs($alpha_flip[$s[$i]]-$alpha_flip[$s[$j]]);
++$i;
--$j;
}
return $sol;
}
echo theLoveLetterMystery('abbc')// return 2
This is my answer for half of half question in SPOJ( Question ID :12156) . I'm a beginner in JAVA. Please Help why am i getting an error. I'm able to get an expected answer while compiling in Ideone. Thanks
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan =new Scanner(System.in);
String[] name= new String[10];
int size,count;
String temp,news;
char[] chars= new char[20];
temp=scan.nextLine();
count=Integer.parseInt(temp);
for(int i=0;i<count;i++)
{
name[i]=scan.nextLine();
}
for(int j=0;j<count;j++)
{
news=name[j];
size=news.length();
chars=news.toCharArray();
for(int k=0;k<size/2;k=k+2)
{
System.out.print(chars[k]);
}
System.out.println();
}
}
}
Pay attention to the following points in the problem description:
In the first line of input your are given the positive integer t
(1 <= t <= 100) - the number of test cases.
In your code, you can handle 10 (and not 100) strings at maximum.
String[] name = new String[10];
In the each of the next t lines, you are given a sequence of 2*k
(1 <= k <= 100) characters.
In your code, you can handle 20 (and not 200) characters at maximum.
char[] chars = new char[20];
I did attempt same question half of half at SPOJ, my code is accepted.
I think array initialisation should be based on input.
import java.util.Scanner;
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner scan = new Scanner(System.in);
int testCase = scan.nextInt();
scan.nextLine();
String[] inputStringArray = new String[testCase];
for (int x = 0; x < testCase; x++) {
String input = scan.nextLine();
input = input.replaceAll("\\s+", "");
inputStringArray[x]=input;
System.out.println("#-"+x);
}
for(int y=0;y<testCase;y++){
String text = inputStringArray[y];
char[] inputArray = text.toCharArray();
int len = inputArray.length/2;
for(int z=0;z<len;z=z+2){
System.out.print(inputArray[z]);
}
System.out.println("");
}
}
}
I am trying to solve a practice question of CodeChef . In this problem we are given N numbers Ai...An and we first have to sort(ascending order) the numbers and then add the alternate numbers starting from the last and show the output for each test cases , the test cases has 2 parts :
1>Constraints :
1 ≤ Ai ≤ 109
1 ≤ N ≤ 1000
2>Constraints:
1 ≤ Ai ≤ 109
1 ≤ N ≤ 105
You can see the full problem here.
The first part of my problem was successfully submitted but second part showed NZEC because I was using long to add those numbers(which was beyond that range). So I decided to use Strings to add up my numbers here is the method :
public static String myStringWayToAdd(String first , String second){
String temp = "";
if(first.length() < second.length()){
temp = first;
first = second;
second = temp;
}
temp = "";
int carry = 0;
for(int i=1;i<=first.length();++i){
if(i <= second.length()){
carry += Integer.parseInt(first.charAt(first.length()-i)+"") + Integer.parseInt(second.charAt(second.length()-i)+"");
}
else{
carry += Integer.parseInt(first.charAt(first.length()-i)+"");
}
temp += carry%10;
carry = carry/10;
}
if(carry != 0)
temp += carry;
StringBuilder myResult = new StringBuilder(temp);
return(myResult.reverse().toString());
}
But now it shows TLE(Time Limit Expire) , So then I thought to use BigInteger(which I am not pretty much Aware of but I saw some tutorials) :
BigInteger big = new BigInteger("0");
big = big.add(BigInteger.valueOf(mySort.get(j))); //for addition and mySort is my ArrayList
But this gave me NZEC I don't know whywell now I want to use double variable but there is a problem with that too, because with double large numbers will be in form of exponential value like :
1.243536E15 which will not be accepted by the machine, so is there any good way to solve this problem and not getting any Time Limit Expiry?.
Any help will really be appreciated. Thank you in Advance.
Edit 1 :
I changed baxck the variable to long and run and this time strangely I got TLE here is my code :
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.math.BigInteger;
import java.lang.Number;
class CFEA{
public static void main(String[] s){
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
for(int i = 0 ; i<testCases;++i){
long sum = 0;
//BigInteger big = new BigInteger("0");
ArrayList<Integer> mySort = new ArrayList<Integer>();
int n = scan.nextInt();
for(int j = 1 ; j <= n ; ++j){
mySort.add(scan.nextInt());
}
Collections.sort(mySort);
for(int j = mySort.size()-1 ; j >= 0 ; j=j-2){
sum += mySort.get(j);
}
System.out.println(sum);
}
}
}
And here is Link to my submission.Is there Anything I can optimize in my code?
The sum of all number is at most 10^9 * 10^5 = 10^14. It is small enough to fit into long. There is no need to use BigInteger.
java.util.Scanner has performance issues. You can implement a custom scanner(using BufferedReader) to speed up your code.
Here is my implementation of a scanner:
import java.io.*;
import java.util.StringTokenizer;
public class FastScanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = reader.readLine();
if (line == null)
throw new IOException();
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public void close() {
try {
reader.close();
} catch (IOException e) {
//ignore
}
}
}
I did some changes in my Program and it was All Accepted a much relief after submitting for about 20 times , here is my new code :
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
class CFEA{
public static void main(String[] s){
Scanner scan = new Scanner(System.in);
byte testCases = Byte.parseByte(scan.nextLine()); //used byte for test cases instead of int
for(int i = 0 ; i<testCases;++i){
long sum = 0;
//BigInteger big = new BigInteger("0");
ArrayList<Integer> mySort = new ArrayList<Integer>();
int n = Integer.parseInt(scan.nextLine());
String input = scan.nextLine();
String[] my = input.split(" ");
for(String myString : my){
mySort.add(Integer.parseInt(myString));
}
Collections.sort(mySort);
for(int j = mySort.size()-1 ; j >= 0 ; j=j-2){
sum += mySort.get(j);
}
System.out.println(sum);
}
}
}
I think the main villain was that I was scanning for Integers N number of times as in this :
for(int j = 1 ; j <= n ; ++j){
mySort.add(scan.nextInt());
}
When N was something Like 100000 then this really slows it down.So i used 1 String for complete line and then Split it into Integers using split method as in :
String input = scan.nextLine(); //only 1 Scanner
String[] my = input.split(" ");
for(String myString : my){
mySort.add(Integer.parseInt(myString));
}
Although My code got submitted I still think there is Further scope for optimization , so please do answer if you have something better
I am solving this question.
This is my code:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] t = new int[n];
int count = 0;
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt();
if (t[i] % k == 0) {
count++;
}
}
System.out.println(count);
}
}
But when I submit it, it get's timed out. Please help me optimize this to as much as is possible.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
They say :
You are expected to be able to process
at least 2.5MB of input data per
second at runtime.
Modified CODE
Thank you all...I modified my code and it worked...here it is....
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
int n = Integer.parseInt(input[0]);
int k = Integer.parseInt(input[1]);
int count = 0;
for (int i = 0; i < n; i++) {
if (Integer.parseInt(br.readLine()) % k == 0) {
count++;
}
}
System.out.println(count);
}
regards
shahensha
This could be slightly faster, based on limc's solution, BufferedReader should be faster still though.
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int count = 0;
while (true) {
try {
if (sc.nextInt() % k == 0) {
count++;
}
} catch (NoSuchElementException e) {
break;
}
}
System.out.println(count);
}
}
How about this?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int count = 0;
for (int i = 0; i < n; i++) {
if (sc.nextInt() % k == 0) {
count++;
}
}
System.out.println(count);
You may consider reading big chunks of input and then get the numbers from there.
Other change is, you may use Integer.parseInt() instead of Scanner.nextInt() although I don't know the details of each one, somethings tells me Scanner version performs a bit more computation to know if the input is correct. Another alternative is to convert the number yourself ( although Integer.parseInt should be fast enough )
Create a sample input, and measure your code, change a bit here and there and see what the difference is.
Measure, measure!
BufferedReader is supposed to be faster than Scanner. You will need to parse everything yourself though and depending on your implementation it could be worse.