Read N Characters Given Read4

easy string simulation interactive

Problem

You are given a file and an API read4(buf) that reads up to 4 characters from the file into buf and returns the number actually read. Implement read(buf, n) that reads exactly n characters (or until end of file) using read4 only.

Inputfile = "abcdefg", n = 5
Output5 (buf = "abcde")
First read4 returns 4 ("abcd"). Second read4 returns 3 ("efg") but only 1 char ("e") is needed.

def read(buf, n):
    total = 0
    tmp = [''] * 4
    while total < n:
        ret = read4(tmp)
        copy = min(ret, n - total)
        for i in range(copy):
            buf[total + i] = tmp[i]
        total += copy
        if ret < 4:
            break
    return total
function read(buf, n) {
  let total = 0;
  const tmp = new Array(4);
  while (total < n) {
    const ret = read4(tmp);
    const copy = Math.min(ret, n - total);
    for (let i = 0; i < copy; i++) buf[total + i] = tmp[i];
    total += copy;
    if (ret < 4) break;
  }
  return total;
}
public class Solution extends Reader4 {
    public int read(char[] buf, int n) {
        int total = 0;
        char[] tmp = new char[4];
        while (total < n) {
            int ret = read4(tmp);
            int copy = Math.min(ret, n - total);
            for (int i = 0; i < copy; i++) buf[total + i] = tmp[i];
            total += copy;
            if (ret < 4) break;
        }
        return total;
    }
}
int read(char* buf, int n) {
    int total = 0;
    char tmp[4];
    while (total < n) {
        int ret = read4(tmp);
        int copy = min(ret, n - total);
        for (int i = 0; i < copy; i++) buf[total + i] = tmp[i];
        total += copy;
        if (ret < 4) break;
    }
    return total;
}
Time: O(n) Space: O(1)