Facebook Interview Question
SDE1sCountry: United States
package fun;
public class BufferRead {
private static int BufSize = 4000;
private char[] extraRead = new char[BufSize];
private int extraBytes = 0;
private int extraBytesStart = 0;
private int extraBytesEnd = 0;
private boolean EOFencountered = false;
private int read4K(char[] buf) {
return 0;
}
// IMPLEMENT:
public int read(char[] buf, int toRead) {
if (EOFencountered) {
return 0;
}
int localtoRead = 0;
while (localtoRead < extraBytes && localtoRead < toRead && extraBytesStart < extraBytesEnd) {
buf[localtoRead++] = extraRead[extraBytesStart++ % BufSize];
}
while (localtoRead < toRead) {
char[] buf4k = new char[4000];
int buytesRead = read4K(buf4k);
int i = localtoRead;
for (; i < localtoRead + buytesRead && i < toRead; i++) {
buf[i] = buf4k[i - localtoRead];
}
// Store the extra Bytes
extraBytesStart = 0;
for (int j = i - localtoRead; j < buytesRead; j++) {
extraRead[extraBytesStart++] = buf4k[j];
}
extraBytesEnd = extraBytesStart;
extraBytesStart = 0;
localtoRead = i;
if (buf[localtoRead - 1] == 0) {
extraBytes = 0;
EOFencountered = true;
break;
}
}
return localtoRead;
}
}
public static void main(String[] args) {
char[] buf = new char[6];
read(buf, 6);
System.out.println("Read the string: " + new String(buf));
}
private static final int C_CHUNK_SIZE = 4;
private static Random random = new Random();
private static void readChunk(char[] buf) throws IOException {
Arrays.fill(buf, 'a');
if(random.nextBoolean())
throw new IOException("Something went wrong");
if(random.nextBoolean())
buf[buf.length-1] = '\0';
}
private static void read(char[] buf, int length) {
int lastIndex = 0;
char[] temp = new char[C_CHUNK_SIZE];
while(lastIndex < length) {
try {
readChunk(temp);
for(int i=0; i < temp.length && lastIndex < length; i++) {
if (temp[i] == '\0')
return;
buf[lastIndex++] = temp[i];
}
} catch (IOException e) {
System.out.println("There was an error reading, will try again...");
}
}
}
- Vibhav May 12, 2017