Skip to content

Instantly share code, notes, and snippets.

@engtomhat
Last active June 11, 2019 03:59
Show Gist options
  • Save engtomhat/589eae9f85f89908b7b81a543069850d to your computer and use it in GitHub Desktop.
Save engtomhat/589eae9f85f89908b7b81a543069850d to your computer and use it in GitHub Desktop.
157. Read N Characters Given Read4
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char[] buf);
*/
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
public int read(char[] buf, int n) {
// System.out.printf("Initial buffer: %s\n", Arrays.toString(buf));
int insertionIndex = 0;
int remainingChars = n - insertionIndex;
char[] buffer = new char[4];
boolean reachedEnd = false;
while (!reachedEnd && remainingChars > 0) {
int charsRead = read4(buffer);
// System.out.printf("Read %d chars into buffer: %s\n", charsRead, Arrays.toString(buffer));
if (charsRead < 4) {
reachedEnd = true;
}
int charsToWrite = remainingChars < charsRead ? remainingChars : charsRead;
for (int i = 0; i < charsToWrite; i++, insertionIndex++) {
buf[insertionIndex] = buffer[i];
}
remainingChars = n - insertionIndex;
// System.out.printf("insertionIndex: %d\tremainingChars: %d\treachedEnd: %b\tResult buffer: %s\n", insertionIndex, remainingChars, reachedEnd, Arrays.toString(buf));
}
return insertionIndex;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment