Meta — Read N Characters Given read4 (Buffered Read)

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem (Meta Unique)

Given read4(buf) which reads up to 4 chars at a time, implement:

  • Version 1: read(buf, n) — call once
  • Version 2: read(buf, n) — may be called multiple times

Solutions

Python — Version 1 (Call Once)

def read(self, buf, n):
    total = 0
    tmp = [''] * 4
    while total < n:
        count = read4(tmp)
        count = min(count, n - total)
        buf[total:total+count] = tmp[:count]
        total += count
        if count < 4:
            break
    return total

Python — Version 2 (Call Multiple Times)

class Solution:
    def __init__(self):
        self.buf4 = [''] * 4
        self.buf4_idx = 0
        self.buf4_count = 0

    def read(self, buf, n):
        total = 0
        while total < n:
            if self.buf4_idx == self.buf4_count:
                self.buf4_count = read4(self.buf4)
                self.buf4_idx = 0
                if self.buf4_count == 0:
                    break
            buf[total] = self.buf4[self.buf4_idx]
            self.buf4_idx += 1
            total += 1
        return total

JavaScript

const read = (buf, n) => {
    let total = 0;
    const tmp = new Array(4);
    while (total < n) {
        const count = Math.min(read4(tmp), n - total);
        for (let i = 0; i < count; i++) buf[total++] = tmp[i];
        if (count < 4) break;
    }
    return total;
};

Java

public int read(char[] buf, int n) {
    int total = 0; char[] tmp = new char[4];
    while (total < n) {
        int count = Math.min(read4(tmp), n-total);
        System.arraycopy(tmp,0,buf,total,count);
        total += count;
        if (count < 4) break;
    }
    return total;
}

C++

int read(char* buf, int n) {
    int total=0; char tmp[4];
    while (total<n) {
        int count=min(read4(tmp),n-total);
        memcpy(buf+total,tmp,count);
        total+=count;
        if (count<4) break;
    }
    return total;
}

C

int read_file(char* buf, int n) {
    int total=0; char tmp[4];
    while (total<n){
        int count=read4(tmp); count=count<n-total?count:n-total;
        for(int i=0;i<count;i++) buf[total++]=tmp[i];
        if(count<4) break;
    }
    return total;
}

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro