Fast Input in Java-2

In the previous Blog, we talked about Buffered Reader for Fast I/O.

Some of you are wondering if there is a fast alternative to the BufferedReader. The following class is an alternative to the BufferedReader


static class InputReader {
	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public String nextToken() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

You can use this class as mentioned in Fast Input in Java.

Advertisements

Fast Input in Java

In many questions of contest, we have to read very large Input. The Scanner class is slow and may cause a time limit exceeded. We can read the input faster with the BufferedReader and BufferedInputStream. but the only bad thing is that you have to worry about the input format means BufferedReader can read only one character or one line. So we have to read Line and split that line by delimiter and convert each resulted string to integer or long or double. Instead of using string.split(” “), we can use StringTokenizer which is faster than earlier one.

All this things  become very complex and take very much time. Time is very important especially when you are participating in  short contest. So instead of writing all this things every time we can make Reusable code.


import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

class MyScanner {
   BufferedReader br;
   StringTokenizer st;
 
   public MyScanner() {
      br = new BufferedReader(new InputStreamReader(System.in));
   }
 
   String next() {
      while (st == null || !st.hasMoreElements()) {
         try {
            st = new StringTokenizer(br.readLine());
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
      return st.nextToken();
   }
 
   int nextInt() {
      return Integer.parseInt(next());
   }
 
   long nextLong() {
      return Long.parseLong(next());
   }
 
   double nextDouble() {
      return Double.parseDouble(next());
   }
 
   String nextLine(){
      String str = "";
      try {
         str = br.readLine();
      } catch (IOException e) {
         e.printStackTrace();
      }
      return str;
   }

}

How to use it?

Copy MyScanner class in your code. and you can use it by making object of it. It is same as Scanner.

class YourClassName
{
    public static void main(String[] args)
    {
        MyScanner s=new MyScanner();

        int t=s.nextInt(); // read an Interger
        System.out.println(t);

        long l=s.nextLong(); // read a Long
        System.out.println(l);

        String word=s.next(); // read a word
        System.out.println(word);

        String str=s.nextLine(); // read whole line
        System.out.println(str);
    }
}

Fast Input Output In CPP /C

Fast Input/Output in C

Have You ever get Time limit Exceeded due to the slow input/output in C.

Its better to  use the following function while taking input from the console .

#define gc getchar_unlocked
int read_int() {
  char c = gc();
  while(c<'0' || c>'9') c = gc();
  int ret = 0;
  while(c>='0' && c<='9') {
    ret = 10 * ret + c - 48;
    c = gc();
  }
  return ret;
}

On windows while testing , you can change #define gc getchar_unlocked to #define gc getchar and change back while submitting.

Now to get the string input use the following function-

inline void fastRead_string(char *str)
{
   register char c = 0;
   register int i = 0;

   while (c < 33)
       c = getchar_unlocked();
   while (c != '\n') {
       str[i] = c;
       c = getchar_unlocked();
       i = i + 1;
   }
   str[i] = '';
}

Using these functions:

int main()
{
  int n;
  char s[100];
  read_int(n);
    printf("%d\n", n);

  fastRead_string(s);
    printf("%s\n", s);
  return 0;
}

Fast Input/Output in CPP

With the starting of the main function in cpp you should use the following line to get fast input.

ios::sync_with_stdio(false);