java - UVa online judge #458 time limit exceeded -


i trying solve uva problem 458 - decoder , came following algorithm gives me correct output sample input data, runs longer allowed.

    public class decoder {      public void decoder() {         scanner sc = new scanner(system.in);          while (sc.hasnext()) {              string line = sc.nextline();              (int = 0; < line.length(); i++) {                  if(line.charat(i)>=32 && line.charat(i)<=126)                 system.out.print((char) (line.charat(i) - 7));              }             system.out.println();         }     }  } 

what i've looked into

well have read forums , of solutions pretty similar, have been researching if there way of avoiding for loop running through string , printing out new char. loop inevitable, algorithm's time complexity going n^2.

the problem mentions change ascii printable values, why set condition check if greater or equal 32 , 126. according wikipedia range of printable values.

http://ideone.com/xkbyw9

  1. avoid decoding stream characters. it's ok use bytes if have support ascii.

  2. read , write data in big chunks avoid function/system call overhead.

  3. avoid unnecessary allocations. allocating new string every line.

  4. do not split input lines avoid bad performance small lines.

example:

public static void main(string[] args) throws ioexception {     byte[] buffer = new byte[2048];     while (true) {         int len = system.in.read(buffer);         if (len <= 0) {             break;         }         (int = 0; < len; i++) {             ...         }         system.out.write(buffer, 0, len);     } } 

it process input process binary file. every iteration, read 2048 bytes buffer, process them , write them standard output. program end when eof reached , read returns -1. 2048 buffer size, might want try different sizes , see 1 works best.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -