[LintCode] Read Characters From File - Multiple Calls

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

The read function may be called multiple times.

Solution analysis

If this read function is only called once, then the solution is pretty straightforward. Simply calling read4 until n characters have

been read or the end of file is reached. If EOF is reached, return however many characters are actually read. In the case of

n % 4 != 0, discard the extra characters read during the last read call and return n.

However, since read function may be called multiple times, we can‘t just discard extra read characters as these characters should be

available for the next read call. So we need to buffer the extra characters for future read calls.

So the read function has one more place to read characters from, the buffer the possibly stores the extra unused characters from

previous read calls. As long as we have not read n characters AND there are characters to be read from the buffer OR from the file,

we keep reading.

In the following solution, variable names are intentionally made long and descriptive, to help understanding of the algorithm.

When we have not read n characters, we always try to read more characters from the buffer. Either the buffer already has characters

from previous read calls, or we call read4 to fill the buffer with new characters then read from the buffer.

When idxOfNextCharInBuffer < totalCharReadPerRead4Call is true, it means we have leftover characters from previous read calls.

We read these leftover characters one by one, and check if a total n has been reached each time. If it has, no need to read from the

file, return n.

If idxOfNextCharInBuffer < totalCharReadPerRead4Call is false, it means either the buffer does not have any leftover characters or

we have read all the leftover characters. In either case, we need to reset idxOfNextCharInBuffer to 0 and call read4 to store more

characters in the buffer.  totalCharReadPerRead4Call is also updated to the actual characters read of this read4 call.

If totalCharReadPerRead4Call is 0, it means we‘ve reached EOF and have no more characters to read.

If it is bigger than 0, it means we still have more characters to possibly read n total characters.

The takeaway of this solution is how neat and short it is. The solution you wrote uses the same logic but has more

than 50 lines of code.

The key idea here is to make buffer, idxOfNextCharInBuffer and totalCharReadPerRead4Call instance variables, not

local variables. As long as we use the same instance, its instance variables stay in their life cycle among multiple

read calls. Previous read call correctly updates all 3 instance variables that are used for the next read call.

 1 public class Solution extends Reader4 {
 2     /**
 3      * @param buf destination buffer
 4      * @param n maximum number of characters to read
 5      * @return the number of characters read
 6      */
 7     char[] buffer = new char[4];
 8     int idxOfNextCharInBuffer = 0, totalCharReadPerRead4Call = 0;
 9
10     public int read(char[] buf, int n) {
11         int charReadCnt = 0;
12         while (charReadCnt < n && (idxOfNextCharInBuffer < totalCharReadPerRead4Call || (totalCharReadPerRead4Call = read4(buffer)) > (idxOfNextCharInBuffer = 0))){
13             buf[charReadCnt++] = buffer[idxOfNextCharInBuffer++];
14         }
15         return charReadCnt;
16     }
17 }
时间: 2024-11-08 22:44:29

[LintCode] Read Characters From File - Multiple Calls的相关文章

从文件中读取字符-多次调用read characters from file multiple calls

[抄题]: 接口:int read4(char * buf)一次从文件中读取 4 个字符.返回值是实际读取的字符数. 例如,如果文件中只剩下 3 个字符,则返回 3.通过使用read4 接口,实现从文件读取 n 个字符的函数int read(char * buf,int n). [暴力解法]: 时间分析: 空间分析: [思维问题]: [一句话思路]: [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入): [画图]: 用数组实现队列的原理是:进入时是ta

[转]Wrapping multiple calls to SaveChanges() in a single transaction

本文转自:http://www.binaryintellect.net/articles/165bb877-27ee-4efa-9fa3-40cd0cf69e49.aspx When you make any additions, modifications and deletions to an Entity  Framework DbSet and call SaveChanges(), EF starts a new transaction and executes  all the IN

LintCode: Unique Characters

C++, time: O(n^2) space: O(0) class Solution { public: /** * @param str: a string * @return: a boolean */ bool isUnique(string &str) { // write your code here for (int i=0; i<str.size(); i++) { for (int j=i+1; j<str.size(); j++) { if (str[i] ==

HTML5 File API解读

1,概述 Web应用应该具备处理广泛用户输入问题的能力,例如在Web富应用中,用户希望上传文件到服务器.File API定义了访问文件的基本操作途径,包括文件.文件列表集.错误处理等,同时,File API还定义了描述文件异步处理进程中的一些元数据.接下来,我们一起看看File的应用. 2,FileList接口 接口描述: 1 interface FileList { 2 getter File? item(unsigned long index); 3 readonly attribute u

5105 pa3 Distributed File System based on Quorum Protocol

1 Design document 1.1 System overview We implemented a distributed file system using a quorum based protocol. The basic idea of this protocol is that the clients need to obtain permission from multiple servers before either reading or writing a file

bootstrap file input 代码

{layout name="layout" title="文章添加" /} <form id="defaultForm" role="form" method="POST" action="{:url('/admin/article/add/')}"> <div class="form-group"> <label for="e

ajax form表单提交 input file中的文件

ajax form表单提交 input file中的文件 现今的主流浏览器由于ajax提交form表单无法把文件类型数据提交到后台,供后台处理,可是开发中由于某些原因又不得不用ajax提交文件, 为了解决这个问题我走了不少弯路: 1.用原生的 input file , 不支持ajax上传文件,你肯定会说可以用 ajax form表单上传了呀?不过我后面还要调用上传成功后用js处理一些对话框,所以这种方法排除 2.用了 uploadify 上传插件,弄出来能上传东西,结果不理想:因为不能判断上传的

通过 File API 使用 JavaScript 读取文件

原文地址:http://www.html5rocks.com/zh/tutorials/file/dndfiles/ 简介 HTML5 终于为我们提供了一种通过 File API 规范与本地文件交互的标准方式.为了举例说明其功能,可使用 File API 在向服务器发送图片的过程中创建图片的缩略图预览,或者允许应用程序在用户离线时保存文件引用.另外,您可以使用客户端逻辑来验证上传内容的 mimetype 与其文件扩展名是否匹配,或者限制上传内容的大小. 该规范通过“本地”文件系统提供了多种文件访

HTML5的 input:file上传类型控制

一.input:file属性 属性值有以下几个比较常用: accept:表示可以选择的文件MIME类型,多个MIME类型用英文逗号分开,常用的MIME类型见下表. multiple:是否可以选择多个文件,多个文件时其value值为第一个文件的虚拟路径. 1.accept 只能选择png和gif图片 <input id="fileId1" type="file" accept="image/png,image/gif" name="