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.
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 trying to use user inputted N lines of N characters to do some operations with. But first I need to know N and another int being inputted. When I define N and the other integer K and then write 5 lines (in this case) of 5 characters each the program runs well. But when I use the represented String a (which I then would split into 2 ints, N and K, not shown here to not complicate things), an error occurs. Even if I now input 6 lines, being the 5 last of 5 characters each, the program gives an error of no line found for the multi function. I don't understand what's the problem, and if I remove the string a and just define N and K the program runs well. What's more surprising, the program runs if I use an interactive console instead of text input and write the terms one by one.
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
int N = 5;
int K = 5;
String [][] multi = vetor(N);
I've tried many things, but I can't make sense of this. I didn't find any similar questions, but feel free to redirect me to an explanation.
Edit: This is a similar program one can run (with a possible input down (K<= N)) :
import java.util.Scanner;
import java.util.Arrays;
public class Main {
static int[] numerificar() {
Scanner myObj = new Scanner(System.in);
String Input = myObj.nextLine();
String[] Inputs = Input.split(" ", 0);
int size = Inputs.length;
int [] a = new int [size];
for(int i=0; i<size; i++) {
a[i] = Integer.parseInt(Inputs[i]);}
return a;
}
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int[] a = numerificar();
int N = a[0];
int K = a[1];
int cadeira = 0;
String [][] multi = vetor(N);
for (int i = 0 ; i<N ; i++){
if (cadeira == 1) {
break;
}
for (int k=0; k<N-K+1; k++){
if (cadeira == 1) {
break;
}else if( multi[i][k].equals(".")){
for (int j=0; j<K; j++){
if(multi[i][k+j].equals( "#")){
k+=j;
break;
} else if (j == K-1) {
cadeira = 1;
}
}
}
}
}
System.out.println(cadeira);
}
}
5 3
.#.##
#####
##...
###..
#####
The output should be 1 in this case.
The problem is you are creating more than one Scanner that reads from System.in. When data is readily available, a Scanner object can read more data than you ask from it. The first Scanner, in the numerificar() method, reads more than the first line, and those lines are not available to the second Scanner, in the vetor() method.
Solution: use just one Scanner object in the whole program.
public class Main {
static Scanner globalScanner = new Scanner(System.in);
static int[] numerificar() {
String Input = globalScanner.nextLine();
String[] Inputs = Input.split(" ", 0);
minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}
I am getting these exception while running the code
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Ideone.main(Main.java:22)
I am new at java and unable to resolve this error. Please help !
Here is my code ->
import java.util.*;
import java.lang.*;
import java.io.*;
class etest {
public static void main (String[] args) throws java.lang.Exception{
int n,k;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
//StringTokenizer token = new StringTokenizer(input.readLine());
int total=0;
int values[] = new int[n];
for(int i =0; i<n; i++) {
values[i] = Integer.parseInt(input.readLine());
if ((values[i]%k)==0) {
total++ ;
}
input.close();
}
System.out.println(total);
}
}
I am using the following input sample to run the program.
Thank you so much for any help!
7 3
1
51
966369
7
9
999996
11
your program has too many errors :
You can change your code as below
public static void main(String[] args) throws java.lang.Exception {
int n, k;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
int total = 0;
int values[] = new int[n];
for (int i = 0; i < n; i++) {
values[i] = in.nextInt();
if ((values[i] % k) == 0) {
total++;
}
}
System.out.println(total);
}
1) you should not close BufferedReader it will automatically close input stream also.
2) you don't need Scanner and BufferedReader at the same time. your solution can use any one of them.
3) better to use try-catch while using Integer.parseInt(String str);
if you want to go with BufferedReader then you need to change your code as
public static void main(String[] args) throws java.lang.Exception {
int n, k;
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
String str[]= input.readLine().split(" ");
n = Integer.parseInt(str[0]);
k = Integer.parseInt(str[1]);
int total = 0;
int values[] = new int[n];
for (int i = 0; i < n; i++) {
values[i]=Integer.parseInt(input.readLine());
if ((values[i] % k) == 0) {
total++;
}
}
System.out.println(total);
}
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