INTEST,java : nothing is fast enough

Can anyone explain faster ways of inputing data in Java.
no other method (like DataInputStream,InputStream,Byte arrays) is working faster than BufferedInputStream which is giving sloppy performance itself.
any suggestions??

Lucky for you, there are faster ways :D.

There are two ways Java programmers normally accept input on CodeChef

1. BufferedReader
2. Scanner

BufferedReader is by far faster than Scanner, but Scanner provides some useful methods (i.e nextInt(), hasNext(), etc).

Javadoc for Scanner: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
Javadoc for BufferedReader: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html

I always use BufferedReader. There’s nothing wrong with it, and it provides an efficient way to accept input (which is imperative given Java’s slow speed).

To declare a BufferedReader, you would do this:

BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );

For a Scanner:

Scanner in = new Scanner( System.in );

I’ve provided the two most used methods for accepting input in Java, and out out both of those (just to reiterate), BufferedReader is the best.

The method in BufferedReader to read the next line is readLine(), so if you wanted to input a String, it would look something like this.

BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
String s = in.readLine();

To go further, BufferedWriter is used to outputting data. This is also more efficient than other methods of outputting (i.e System.out.println() );

BufferedWriter javadoc: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html

So if you wanted to use a BufferedWriter, it should look something like this:

BufferedWriter out = new BufferedWriter( new OutputStreamWriter( System.out ) );
out.append( "Text to be outputted" + "\n" ); // "\n" starts a new line.

To be even faster, you could use a PrintWriter to output your data:

PrintWriter out = new PrintWriter( new OutputStreamWriter( System.out ) ) );

So those are your tools for inputting and outputting data :).

3 Likes

Yeah, you are right but in some cases even BufferedReader fails to abide by the time limit(in case of very large data).
And in the codechef java tutorial it says that BufferedInputStream is the faster than both Scanner,BufferedReader.
I have tried all of the above and in every case time limit is exceeded.

I even used Byte arrays with InputStreamReader but that didnt work either.

In this case, it’s most likely your algorithm that’s slow.

1 Like

If you’d like, you may look at other Java programmer solutions http://www.codechef.com/status/INTEST?language=10&status=15&handle=&sort_by=All&sorting_order=asc&Submit=GO

1 Like