@@ -0,0 +1,2550 @@
+package com.interview.misc;%0A%0Aimport java.util.Arrays;%0A%0A/**%0A * Given a reader which only reads 4 bytes implement a Reader which can read bytes of give size.%0A */%0Apublic class Read4Function %7B%0A%0A    private final Reader reader;%0A    private final Queue queue;%0A    public Read4Function() %7B%0A        this.reader = new Reader();%0A        queue = new Queue(4);%0A    %7D%0A%0A    public byte%5B%5D read(int size) %7B%0A        byte%5B%5D output = new byte%5Bsize%5D;%0A        int n = 0;%0A        while (!queue.isEmpty() && n %3C size) %7B%0A            output%5Bn++%5D = queue.poll();%0A        %7D%0A%0A        if (n == size) %7B%0A            return output;%0A        %7D%0A%0A        int remaining = size - n;%0A        byte%5B%5D b = null;%0A        while (remaining %3E 0) %7B%0A            b = reader.read();%0A            copy(b, output, 0, n, remaining %3E 4 ? 4 : remaining);%0A            n += 4;%0A            remaining -= 4;%0A        %7D%0A        for (int i = 4 + remaining; i %3C 4; i++) %7B%0A            queue.offer(b%5Bi%5D);%0A        %7D%0A%0A        return output;%0A    %7D%0A%0A    private void copy(byte%5B%5D src, byte%5B%5D destination, int sourceStart, int destinationStart, int size) %7B%0A        int i = sourceStart;%0A        int j = destinationStart;%0A        while (i %3C sourceStart + size) %7B%0A            destination%5Bj++%5D = src%5Bi++%5D;%0A        %7D%0A    %7D%0A%0A    public static void main(String args%5B%5D) %7B%0A        Read4Function rf = new Read4Function();%0A        System.out.println(Arrays.toString(rf.read(2)));%0A        System.out.println(Arrays.toString(rf.read(1)));%0A        System.out.println(Arrays.toString(rf.read(1)));%0A        System.out.println(Arrays.toString(rf.read(5)));%0A        System.out.println(Arrays.toString(rf.read(2)));%0A        System.out.println(Arrays.toString(rf.read(8)));%0A        System.out.println(Arrays.toString(rf.read(7)));%0A        System.out.println(Arrays.toString(rf.read(17)));%0A        System.out.println(Arrays.toString(rf.read(1)));%0A    %7D%0A%7D%0A%0Aclass Queue %7B%0A    int start;%0A    int end;%0A    int count;%0A    byte%5B%5D data;%0A    int size;%0A    Queue(int size) %7B%0A        data = new byte%5Bsize%5D;%0A        this.size = size;%0A    %7D%0A%0A    boolean isEmpty() %7B%0A        return count == 0;%0A    %7D%0A%0A    void offer(byte b) %7B%0A        data%5Bstart%5D = b;%0A        start = (start + 1)%25size;%0A        count++;%0A    %7D%0A%0A    byte poll() %7B%0A        byte d = data%5Bend%5D;%0A        end = (end + 1)%25size;%0A        count--;%0A        return d;%0A    %7D%0A%7D%0A%0Aclass Reader %7B%0A    int index = 0;%0A    byte%5B%5D read() %7B%0A        byte%5B%5D b = new byte%5B4%5D;%0A        for (int i = index; i %3C index + 4; i++) %7B%0A            b%5Bi - index%5D = (byte)i;%0A        %7D%0A        index += 4;%0A        return b;%0A    %7D%0A%7D%0A

implement read for read4