3.8 Read N Characters Given Read4 II - Call multiple times

Description

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note: The read function may be called multiple times.

Method

I used buffer pointer (buffPtr) and buffer Counter (buffCnt) to store the data received in previous calls. In the while loop, if buffPtr reaches current buffCnt, it will be set as zero to be ready to read new data.

Time and Space Complexity

O(n / 4)

Code

public class Solution extends Reader4 { /**

 * @param buf Destination buffer
 * @param n   Maximum number of characters to read
 * @return    The number of characters read
 */
private char[] buff = new char[4];
private int curbuff = 0;
private int prebuff = 0;

public int read(char[] buf, int n) {

       int index = 0;

       while (index < n){
              if (prebuff == 0) {
                  curbuff = read4(buff);
              }
              if (curbuff == 0){
                  break;
              }
              while (index < n && prebuff < curbuff){
                     buf[index++] = buff[prebuff++];
              }
              if (prebuff >= curbuff){
                  prebuff = 0;
              }
       }
       return index;


}

}

results matching ""

    No results matching ""