Monday, 20 October 2014

Multiple Inputs in same line.

Multiple Inputs in same line.

This one is for beginners!!
Usually the input format in competitive programming questions is as follows:

2 3 2 1 2
1 2 3
4 5 6 1
. ..  so on

If you are new to competitive programming and JAVA(Newbie here too, as in you only have a basic knowledge of java and coded back in high school) is all you know how to code in, then this is an issue you may face. HOW TO TAKE MULTIPLE INPUTS IN SAME LINE IN JAVA!!! (we are avoiding Scanner class here because it is easily the most convenient way of reading in input, however it is very slow and not recommended unless the input is very small. ( less than 50KB of data is to be read ))

Well don't worry here is a solution. I will be discussing a couple of cases which you may face.  

Case 1: Method 1
              1 2 3 4 5
             
Java Code:
                
 Note: use BufferedInputStream for reading inputs in JAVA because it is considered as the fastest way of reading inputs. Scanner class
The following code will read five inputs in same line and print the same.

         import java.io.*;
     class inputMlines{
           public static void main(String[] args)throws IOException{
                             BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
               double[] j= new double[5];
            String[] s2 = inp.readLine().split(" ");
                j[0]=Double.parseDouble(s2[0]);
                j[1]=Double.parseDouble(s2[1]);
                                j[2]=Double.parseDouble(s2[2]);
                j[3]=Double.parseDouble(s2[3]);
                j[4]=Double.parseDouble(s2[4]); 
             for(int i=0;i<5;i++)
                  System.out.print(j[i]+" ");
            }//main function ends
        } // class closed
==================================================================

Case 2: Method 1
       1 2 3
       2 3 3
Java Code:
        the following code takes input in the above format and prints nothing.      

import java.io.*;
     class inputMlines{
           public static void main(String[] args)throws IOException{
                             BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
               double[] j= new double[3];
       for(int input=0;input<2;input++){
            String[] s2 = inp.readLine().split(" ");
                j[0]=Double.parseDouble(s2[0]);
                j[1]=Double.parseDouble(s2[1]);
                                j[2]=Double.parseDouble(s2[2]);
           }//for loop ends.               
            }//main function ends
        } // class closed
you can generalise this method after trying yourself.
==================================================================
That is all for this post. Please leave your QUERIES, SUGGESTIONS, BETTER METHODS OR any CORRECTIONS you think in the comments.
Have a nice day!!