Read N characters given read7
Problem Using a read7() method that returns 7 characters from a file, implement readN(n) which reads n characters. For example, given a file with the content “Hello world”, three read7() returns “Hello w”, “orld” and then “”. Solution Method 1 - Using Iteration Here are the steps: Buffer Management: Maintain a buffer to store characters read by read7() that weren’t consumed by readN(n) calls. Reading n Characters: Continuously read using read7() until we have at least n characters in total. If read7() returns fewer than 7 characters, we’ve likely reached the end of the file. Serve the Required Characters: Serve characters from the buffer to fulfill the readN(n) request. Code Java public class FileReader { private String content; private int index; public FileReader(String content) { this.content = content; this.index = 0; } public String read7() { if (index >= content.length()) { return ""; } int end = Math.min(index + 7, content.length()); String result = content.substring(index, end); index += 7; return result; } } public class Solution { private FileReader fileReader; private Queue<Character> buffer; public Solution(FileReader fileReader) { this.fileReader = fileReader; this.buffer = new LinkedList<>(); } public String readN(int n) { StringBuilder result = new StringBuilder(); while (result.length() < n) { // If buffer is empty, read more characters using read7() if (buffer.isEmpty()) { String readData = fileReader.read7(); if (readData.isEmpty()) { break; } for (char c : readData.toCharArray()) { buffer.offer(c); } } // Add buffered characters to the result while (!buffer.isEmpty() && result.length() < n) { result.append(buffer.poll()); } } return result.toString(); } } ...