Efficiently Reading Input For Competitive Programming using Java 8As we all know, while solving any CP problems, the very first step is collecting input or reading input. A common mistake we all make is spending too much time on writing code and compile-time as well. In Java, it is recommended to use BufferedReader over Scanner to accept input from the user. Why? It is discussed in one of our previous articles here. (Also, the issues associated with the java.util.Scanner is available) Yet for a better understanding, we will go through both the implementations in this article. Ways of Reading Inputs Using Scanner class Using BufferedReader class Using BufferedReader class with help of streams (More optimized) Now let us discuss ways of reading individually to depth by providing clean java programs and perceiving the output generated from the custom input. Way 1: Simple Scanner Input Reading The java.util.Scanner class provides inbuilt methods to read primitive data from the console along with the lines of text. In the below code snippet let's understand how it is done. The above example illustrates the most common approach used by the majority of programmers while solving competitive programming problems. But what if we can enhance our code a bit to make it faster and reliable? Method 2: Simple BufferedReader Input Reading java.io.BufferedReader class does not provide any method to read primitive data inputs. Java.io.BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of the sequence of characters. Although it throws a checked exception known as IOException. Let us see how to handle that exception and read input from the user. Consider custom input as below as follows: Input: 4 5.6 1 2 3 4 5 Example The above example illustrates another common approach used to read the data while solving competitive programming problems. So is this enough? What if we can enhance it even more? Yes. It is possible. Stay tuned. Method 3: Enhanced way for reading separated data using BufferedReader via Streams In the previous examples, we have seen while reading space-separated data we stored it first in a String array, and then we iterated over elements and then used java typecasting to convert it to the required data type. How about a single line of code making this possible? Yes. Java 8's stream library provides a variety of functions to make it easy and optimized. Consider custom input as below as follows: Input: 34 55 78 43 78 43 22 94 67 96 32 79 6 33 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India