This page explains Java solution to problem Read N Characters Given Read4 II
using String
data structure.
Given a file and assume that you can only read the file using a given method read4, implement a method read to read n characters. Your method read may be called multiple times.
The API read4 reads 4 consecutive characters from the file, then writes those characters into the buffer array buf.
The return value is the number of actual characters read.
Note that read4() has its own file pointer, much like FILE *fp in C.
Example 1:Input: File file("abc")
Output:
Assume buf is allocated and guaranteed to have enough space for storing all characters from the file.
read(buf, 1); // After calling your read method, buf should contain "a". We read a total of 1 character from the file, so return 1.
read(buf, 2); // Now buf should contain "bc". We read a total of 2 characters from the file, so return 2.
read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0.
package com.vc.hard;
import java.util.Random;
class Reader4 {
private Random random = new Random();
public int read4(char[] buf) {
int count = random.nextInt(5);
for(int i = 0; i < count; i++) {
buf[i] = (char) random.nextInt();
}
return count;
}
}
public class ReadNCharactersGivenRead4Ii extends Reader4 {
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
private char[] tempBuf = new char[4];
private int index = 0, tempIndex = 0, charRead = 0;
public int read(char[] buf, int n) {
index = 0;
while(index < n) {
if(charRead == tempIndex) {
tempIndex = 0;
charRead = read4(tempBuf);
if(charRead == 0) break;
}
buf[index++] = tempBuf[tempIndex++];
}
return index;
}
}
O(N) Where
N is total number of elements in an input file
O(N) Where
N is total number of elements in an input file