This is a problem set
This is my realization it works, but i get wrong answer on acm.timus.ru
import java.io.PrintWriter;
import java.util.Scanner;
public class SqrtBack{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int count = 0;
PrintWriter out = new PrintWriter(System.out);
long[] arr = new long[131072];
while(in.hasNextLong()){
arr[count] = in.nextLong();
count++;
}
for(int i = arr.length-1; i>=0; i--){
System.out.printf("%.4f%n", (Math.sqrt(arr[i])));
}
out.flush();
}
}
You are always printing 131072 values even though the input could be fewer... Change your loop to:
for(int i = count - 1; i >= 0; i--) ...
Note: Always try with the sample data when doing problems like this. In this case you would see the problem directly..
Related
Even if I think that I solved a competitive programming problem from HackerEarth with the best approach, all tests exceed the time limit. I really do not know how to optimize it further because it is just an easy exercise.
My approach: iterate over all array members than add them to a HashMap which stores their occurrences. After that simply read the query numbers and get their occurence from the HashMap.
This is my solution:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
class TestClass {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
//go through all test cases
for (int i = 0; i < t; i++) {
Map<Integer, Integer> map = new HashMap<>();
String[] inputs = br.readLine().split(" ");
int N = Integer.parseInt(inputs[0]);
int Q = Integer.parseInt(inputs[1]);
inputs = br.readLine().split(" ");
//read array
for (int j = 0; j < N; j++) {
int x = Integer.parseInt(inputs[j]);
Integer value = map.get(x);
//if number is already in hashmap then increment its count
//else put it into the map with a count of 1
if (value == null) {
map.put(x, 1);
} else map.put(x, value + 1);
}
//iterate through the queries and get their occurences from the map
for (int j = 0; j < Q; j++) {
int x = Integer.parseInt(br.readLine());
Integer value = map.get(x);
if (value == null) {
System.out.println(0);
} else System.out.println(value);
}
}
}
}
My question is: what can be the problem with my approach? Why does it run out of time?
Ok, so the problem is not so obvious. I took a look at the input files and they are huge so you have to use some really fast method for writing to the console(many test cases -->> many answers). You can use PrinteWriter for that.
Working solution:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
class TestClass {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
//go through all test cases
for (int i = 0; i < t; i++) {
Map<Integer, Integer> map = new HashMap<>();
String[] inputs = br.readLine().split(" ");
int N = Integer.parseInt(inputs[0]);
int Q = Integer.parseInt(inputs[1]);
inputs = br.readLine().split(" ");
//read array
for (int j = 0; j < N; j++) {
int x = Integer.parseInt(inputs[j]);
Integer value = map.get(x);
//if number is already in hashmap then increment its count
//else put it into the map with a count of 1
if (value == null) {
map.put(x, 1);
} else map.put(x, value + 1);
}
//iterate through the queries and get their occurences from the map
for (int j = 0; j < Q; j++) {
int x = Integer.parseInt(br.readLine());
Integer value = map.get(x);
if (value == null) {
pr.println(0);
} else pr.println(value);
}
}
pr.close();
}
}
Yes, I know that it is strange that the exercise itself is not so hard, but reading the input and writing the result is the big part of it.
The problem with your approach is primarily it's use of BufferedReader, and the consequential information parsing you're preforming. Try an approach with scanner.
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
int T = s.nextInt();
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<T;i++)
{
StringBuilder sb=new StringBuilder();
int N=s.nextInt();
int Q=s.nextInt();
int[] arr=new int[N];
for(int j=0;j<N;j++)
{
arr[j]=s.nextInt();
if(map.containsKey(arr[j]))
{
map.put(arr[j],map.get(arr[j])+1);
}
else
map.put(arr[j],1);
}
for(int k=0;k<Q;k++)
{
int X=s.nextInt();
if(map.containsKey(X)){
sb.append(map.get(X)+"\n");
}
else{
sb.append(0+"\n");
}
}
System.out.println(sb.toString());
map.clear();
}
}
}
This will remove a lot of the unnecessary parsing you are doing with:
String[] inputs = br.readLine().split(" ");
int N = Integer.parseInt(inputs[0]);
int Q = Integer.parseInt(inputs[1]);
inputs = br.readLine().split(" ");
Please look at Scanner vs. BufferedReader to understand why Scanner is situationally faster here. Essentially BufferedReader is faster in it's ability to simply read the lines, but when you use BufferedReader here, you are then forced to use Integer.parseInt(...) and br.readlines().split(" ") to parse the information you need from the input; however, scanner has built in parsing mechanisms that can read and parse the data asynchronously. As you will see, this approach passes the test in 4-8 seconds. Additionally you could benefit from using StringBuilder, and not using:
Integer value = map.get(x);
if (value == null) {
pr.println(0);
} else pr.println(value);
With the built in method map.containsKey(x).
Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special
parsing.
In fact you can pass a BufferedReader to a scanner as the source of
characters to parse.
Furthermore:
A scanner on the other hand has a lot more cheese built into it; it
can do all that a BufferedReader can do and at around the same level of
efficiency as well. However, in addition a Scanner can parse the
underlying stream for primitive types and strings using regular
expressions. It can also tokenize the underlying stream with the
delimiter of your choice. It can also do forward scanning of the
underlying stream disregarding the delimiter!
There is a large difference in runtime when you have to call
inputs = br.readLine().split(" "); and Integer.parseInt(..) multiple times, versus simply calling s.nextInt(). You are already reading the data with br.readLine(), when you call Integer.parseInt(...) the data is read again by the parseInt() function.
I am trying to bubble sort numbers from a text file, I understand how to bubble sort and how to use a text file. But have never used both of them at the same time. I tried bubble sorting an array and just trying to figure out how to replace that array with a text file. If someone can explain to me how to get the bubble sort to read a text file it would be greatly appreciated. I am new to java and it is sometimes confusing to combine 2 different things I have learned into 1 program.
Here is my bubble sort that solves the array:
public static void main(String[] args)
{
int number[]={7,13,4,5,62,3,1,3,45};
int temp;
boolean fixed=false;
while(fixed==false){
fixed = true;
for (int i=0; i <number.length-1;i++){
if (number[i]>number[i+1]){
temp = number [i+1];
number[i+1]=number[i];
number[i]=temp;
fixed=false;
}
}
}
for (int i=0; i<number.length;i++){
System.out.println(number[i]);
}
}
}
Use Scanner class !
File file=new File("file.txt");
Scanner sc=new Scanner(file);
int arr[]=new int[100];
int i=0;
while(sc.hasNextLine()){
arr[i]=sc.nextInt();
i++;
}
Don't just hard code the array..!
Suppose the content of your file is a list of number separated by some delimiter say single space " "
Use:
File file=new File("file.txt");
Scanner sc=new Scanner(file);
String arr[] = sc.nextLine().split(" ");
That is it.
Once you have got the array u can play around with it..!
Reading a file has nothing to do with bubble sort. You can read the file to create an array of integers and then use the usual bubble sort algorithm to sort it
You can do like this:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void bubbleSort(int[] num ) {
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag ) {
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ ) {
if ( num[ j ] < num[j+1] ) {
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int [] numbers = new int [256];
int i = 0;
while(scanner.hasNextInt()){
numbers[i++] = scanner.nextInt();
}
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
I have been testing my code for the overlapping rectangles challenge on codeeval. I feel my code is close to the solution as I have tested it on my machine and it appears correct. Codeeval is picky however and won't execute the code, claiming it is hanging.No further information is given. It has done this in the past but that was due to me not closing my scanner at the end. Am I violating a similar principle here?
Any recommendations on finding the solution simpler or better coding practices is appreciated.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:/Users/minda_000/Desktop/text.txt");
FileReader fr = new FileReader(file);
Scanner scan = new Scanner(fr);
scan.useDelimiter(",");
boolean flag = true;
while (scan.hasNextLine()) {
String line = scan.nextLine();
Scanner scanline = new Scanner(line);
scanline.useDelimiter(",");
int lxa = scanline.nextInt();
int lya = scanline.nextInt();
int rxa = scanline.nextInt();
int rya = scanline.nextInt();
int lxb = scanline.nextInt();
int lyb = scanline.nextInt();
int rxb = scanline.nextInt();
int ryb = scanline.nextInt();
int[] contentsofx = contentsOfX(lxa, rxa);
int[] contentsofy = contentsOfY(lya, rya);
int[] contentsofx2 = contentsOfX(lxb, rxb);
int[] contentsofy2 = contentsOfY(lyb, ryb);
scanline.close();
for (int i = 0; i < contentsofx.length; i++) {
for (int j = 0; j < contentsofx2.length; j++) {
if (contentsofx[i] == contentsofx2[j]) {
if(i<contentsofy.length && i<contentsofy2.length && contentsofy[i]==contentsofy2[j]){
System.out.println(true);
flag=false;
}
}
}
}
if(flag) {
System.out.println(false);
}
flag=true;
}
scan.close();
}
public static int[] contentsOfX(int lx, int rx) {
int[] line = new int[(rx - lx)];
for (int i = 0; i < line.length; i++) {
line[i] = lx + i;
}
return line;
}
public static int[] contentsOfY(int ly, int ry) {
int[] line = new int[(ly - ry)];
for (int i = 0; i < line.length; i++) {
line[i] = ry + i;
}
return line;
}
}
Just to make sure, you are changing "C:/Users/minda_000/Desktop/text.txt" to args[0] before uploading your solution to CodeEval, right?
Some of the other issues:
You're outputting True and False in lowercase when they're supposed to be capitalized.
In this line --
if(i<contentsofy.length && i<contentsofy2.length && contentsofy[i]==contentsofy2[j]){
-- you've got a problem when i and/or j are larger than the lengths of contentsofy and contentsofy2.
And comments would make your code easier to read. :-)
I scrapped this code and started over more or less with a much cleaner solution just using boolean logic. The problems with this code is the contentsOfX and contentsOfY methods should be 1 size greater for one point overlap. Additionally, at this time I implied one rectangle would always be to the left of the other. The nested for loop does not work as intended because of this. Still the arrays are sorted for each value from minimum value of x,y to maximum value of x,y so if you check for the reverse polarity index within the array as well the logic should be the work.
The exercise I'm trying right now will require me to to
Gather 10 values from the user to store into an array
Display the mode of the 10 values
(possible using a parallel array to count the occurrences of the values)
use a method to use entered values as a parameter for and return the array with max values in order
This is the code I have so far:
The issue is that my mode worked for 10 DEFINED values but once I tried to mess with it and add the scanner for the values I lost myself
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arraytwo = {10};
test3(arraytwo);
number = scan.nextInt;
number = arraytwo[i];
}
public static void test3(int[] array)
{
int modeTrack[] = new int[10];
int max =0; int number =0;
for (int i = 0; i < array.length; i++)
{
modeTrack[array[i]] += 1;
}
int maxIndex = 0;
for (int i = 1; i < modeTrack.length; i++)
{
int newNum = modeTrack[i];
if (newNum > modeTrack[maxIndex])
{
maxIndex = i;
}
}System.out.println(maxIndex);
}
This code will take ten values and sort them in descending order..Hope it will help you..save below code in Test.java and run it
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Integer[] array = new Integer[10];
Scanner scan = new Scanner(System.in);
for (int i = 0; i <10; i++) {
array[i] = scan.nextInt();
}
doSort(array);
}
static void doSort(Integer[] array)
{
Arrays.sort(array,Collections.reverseOrder());
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
It sounds like your test3() method isn't what's giving you trouble so I'll talk a bit about your main() method.
You have a few errors in your main() denoted by comments I have inserted:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arraytwo = {10};
test3(arraytwo);
number = scan.nextInt; //number does not exist in this scope, also nextInt method should use () to call it.
number = arraytwo[i]; //i does not exist in this scope
}
For the main method, I suggest you do something like the following:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Integer[] arrTwo = new Integer[10];
for (int i = 0; i < 10; i++)
{
arrTwo[i] = scan.nextInt();
}
sort(arrTwo);
//System.out.println(Arrays.toString(arrTwo)); //this line will print your sorted array for you..
}
For the sort method you could do something like the following:
public static void sort(Integer[] arr){
Arrays.sort(arr, Collections.reverseOrder());
}
package primesieve1;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Primesieve1 {
public boolean[] sieveOfEratosthenes(int max){
boolean[] primeno; //defaults to false
primeno = new boolean[max];
for(int i=2; i<max; i++ ){primeno[i]=true;}
for(int i=2; i<Math.sqrt(max);i++){
if(primeno[i] == true){
//all multiples of i*i, except i, are not primeno
for(int j = i + i; j<max; j=j+i){
primeno[j]=false;
}
}
}
return primeno;
}
public void printTrue(boolean[] arr){
for(int i=0; i<arr.length; i++){
if(arr[i]==true){
System.out.print(i + ", ");
}
}
}
public static void main(String[] args) {
System.out.println("enter limit");
Scanner sc = new Scanner(new InputStreamReader(System.in));
int a = sc.nextInt();
boolean a1[];
Primesieve1 obj = new Primesieve1();
a1 = obj.sieveOfEratosthenes(a);
obj.printTrue(a1);
}
}
giving out this error didnt understand why
java.lang.OutOfMemoryError: Java heap space
Although I'm not 100% sure I think a boolean[] still uses about 1 byte per entry. Max will probably get quite big so even increasing the memory for the JVM will probably not do the trick.
One thing you can do however is not use a boolean[] but a BitSet instead, this way you'll only use 1 bit per number and thus you can probably cover until the max value of int.