ip696
ip696

Reputation: 7084

more efficiently read int values from console

How can I read int values from console more efficiently (from memory) than this:

BufferedReader in ...
number = Integer.parseInt(in.readLine());

When I use readLine() and parse it to int, java create many String objects and сonsumes memory. I try to use Scanner and method nextInt() but this approach is also not that efficiently.

P.S I need read > 1000_000 values and I have memory limit.

EDIT Full code of task

import java.io.*;

public class Duplicate {

    public static void main(String[] args) throws IOException {

        int last = 0;
        boolean b = false;

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

        int n = Integer.parseInt(reader.readLine());

        for (int i = 0; i < n; i++) {
            int number =Integer.parseInt(reader.readLine());
            if (number == 0 && !b) {
                System.out.println(0);
                b = true;
            }
            if (number == last) continue;
            last = number;
            System.out.print(last);
        }
    }
}

And Rewrite variant:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class Duplicate {

    public static void main(String[] args) throws IOException {

        int last = 0;
        boolean b = false;

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int nextInt = getNextInt(reader);

        for (int i = 0; i < nextInt; i++) {
            int number = getNextInt(reader);
            if (number == 0 && !b) {
                System.out.println(0);
                b = true;
            }
            if (number == last) continue;
            b = true;
            last = number;
            System.out.println(last);
        }
    }

    static int getNextInt(Reader in) throws IOException {
        int c;
        boolean negative = false;
        do {
            c = in.read();
            if (!Character.isDigit(c)) {
                negative = c == '-';
            }
        } while (c != -1 && !Character.isDigit(c));
        if (c == -1) return Integer.MIN_VALUE;

        int num = Character.getNumericValue(c);
        while ((c = in.read()) != -1 && Character.isDigit(c)) {
            num = 10 * num + Character.getNumericValue(c);
        }
        return negative ? -num : num;
    }
}

Both options do not pass from memory (((

enter image description here

EDIT2 I try profiling

int number = getRandom(); and start with 1000000

enter image description here

once again launched the same enter image description here

and splash GC

enter image description here

Upvotes: 0

Views: 81

Answers (3)

shakhawat
shakhawat

Reputation: 2727

I use this InputReader on codeforces. Works pretty well for me on large input cases. You can extend this up to your use case. I came across this after getting TLE using Scanner and add functionalities if needed.

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

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

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

    public int readInt() {
        return (int) readLong();
    }

    public long readLong() {
        int c = read();
        while (isSpaceChar(c)) {
            c = read();
            if (c == -1) throw new RuntimeException();
        }
        boolean negative = false;
        if (c == '-') {
            negative = true;
            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 negative ? (-res) : (res);
    }

    public int[] readIntArray(int size) {
        int[] arr = new int[size];
        for (int i = 0; i < size; i++) arr[i] = readInt();
        return arr;
    }

    private boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

}

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140319

You can read from in one char at a time, checking if it's a digit, and then accumulating it into a number. Something like:

int getNextInt(Reader in) throws IOException {
  int c;
  boolean negative = false;
  do {
    c = in.read();
    if (!Character.isDigit(c)) { negative = c == '-' };
  } while (c != -1 && !Character.isDigit(c));
  if (c == -1) return Integer.MIN_VALUE;  // Some sentinel to indicate nothing found.

  int num = Character.getNumericValue(c);
  while ((c = in.read()) != -1 && Character.isDigit(c)) {
    num = 10 * num + Character.getNumericValue(c);
  }
  return negative ? -num : num;
}

Ideone demo

Of course, this is incredibly primitive parsing. But you could perhaps take this code as a basis and adapt it as required.

Upvotes: 1

shakhawat
shakhawat

Reputation: 2727

You can use this FastScanner class

static class FastScanner {
    private BufferedReader reader = null;
    private StringTokenizer tokenizer = null;

    public FastScanner(InputStream in) {
        reader = new BufferedReader(new InputStreamReader(in));
        tokenizer = null;
    }

    public String next() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    public String nextLine() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                return reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return tokenizer.nextToken("\n");
    }

    public long nextLong() {
        return Long.parseLong(next());
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }
}

It is very commonly used on codeforces to read large input where Scanner class leads to TLE

This is originally authored by https://codeforces.com/profile/Petr

Upvotes: 0

Related Questions