博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
499 单词计数 (Map Reduce版本)
阅读量:4678 次
发布时间:2019-06-09

本文共 2800 字,大约阅读时间需要 9 分钟。

原题网址:

描述

使用 map reduce 来计算单词频率

https://hadoop.apache.org/docs/r1.2.1/mapred_tutorial.html#Example%3A+WordCount+v1.0

您在真实的面试中是否遇到过这个题?  是

样例

chunk1: "Google Bye GoodBye Hadoop code"chunk2: "lintcode code Bye"Get MapReduce result:    Bye: 2    GoodBye: 1    Google: 1    Hadoop: 1    code: 2    lintcode: 1
标签
Big Data
Map Reduce
 
 
思路:没怎么看懂这道题什么意思,参照着网上的代码捋了一遍。
Map类负责对原始数据进行处理,将字符串拆分成单词后输出到output; Reduce负责对Map输出的数据进行计数。

即:

map函数对输入的文本进行分词处理,然后输出(单词, 1)这样的结果,例如“You are a young man”,输出的就是(you, 1), (are, 1) 之类的结果;

在reduce函数中,我们把具有相同key的结果聚合起来。reduce函数的第二个参数类型为Input<int>, 这是一堆value的集合,他们具有相同的key,reduce函数的意义就是将这些结果聚合起来。

例如(”hello“, 1)和(”hello“, 1)聚合为(”hello“, 2),后者可能再次和(”hello“, 3) (”hello“, 1),聚合为(”hello“, 7)。  

 
 
AC代码:
/** * Definition of Input: * template
* class Input { * public: * bool done(); * // Returns true if the iteration has elements or false. * void next(); * // Move to the next element in the iteration * // Runtime error if the iteration has no more elements * T value(); * // Get the current element, Runtime error if * // the iteration has no more elements * } */class WordCountMapper: public Mapper {public: void Map(Input
* input) { // Write your code here // Please directly use func 'output' to // output the results into output buffer. // void output(string &key, int value); vector
vecStr; //没看懂这句是干什么的……; while(!input->done())//为什么判断句不是input->done(); { string str=input->value(); int j=0; for(int i=0;i<=(int)str.size();i++)//注意判断句是小于等于; { if(str[i]==' '||i==str.size()) { string temp=str.substr(j,i-j); output(temp,1); j=i+1; } } input->next(); } }};class WordCountReducer: public Reducer {public: void Reduce(string &key, Input
* input) { // Write your code here // Please directly use func 'output' to // output the results into output buffer. // void output(string &key, int value); int sum=0; while(!input->done()) { sum+=input->value(); input->next(); } output(key,sum); }};

代码中有三处不明白,

第一个是map函数中vector<string>数组的作用,将其注释掉也可以AC;

第二个是 while(!input->done())为什么不是 while(input->done()),done()函数不是如果容器有元素就返回true吗……;

第三个是 for(int i=0;i<=(int)str.size();i++),for循环的判断句为何是小于等于?后来这个问题想明白了,如果只是小于,会漏掉最后一个单词。因为当i为最后一个单词最后一个字符索引时,str【i】不为‘ ’,且i =size-1小于size,导致if块内语句无法执行。

 

其他参考:
 

转载于:https://www.cnblogs.com/Tang-tangt/p/9262392.html

你可能感兴趣的文章