educoder--MapReduce基础实战各关卡通关答案

2023-05-16

第1关:成绩统计:

任务描述
相关知识
什么是MapReduce
如何使用MapReduce进行运算
代码解释
编程要求
测试说明
任务描述
本关任务:使用Map/Reduce计算班级中年龄最大的学生。

相关知识
为了完成本关任务,你需要掌握:1.什么是MapReduce,2.如何使用MapReduce进行运算。

什么是MapReduce
MapReduce是一种可用于数据处理的编程模型,我们现在设想一个场景,你接到一个任务,任务是:挖掘分析我国气象中心近年来的数据日志,该数据日志大小有3T,让你分析计算出每一年的最高气温,如果你现在只有一台计算机,如何处理呢?我想你应该会读取这些数据,并且将读取到的数据与目前的最大气温值进行比较。比较完所有的数据之后就可以得出最高气温了。不过以我们的经验都知道要处理这么多数据肯定是非常耗时的。

如果我现在给你三台机器,你会如何处理呢?看到下图你应该想到了:最好的处理方式是将这些数据切分成三块,然后分别计算处理这些数据(Map),处理完毕之后发送到一台机器上进行合并(merge),再计算合并之后的数据,归纳(reduce)并输出。

这就是一个比较完整的MapReduce的过程了。

开始你的任务吧,祝你成功!

答案代码--------------------------------------

import java.io.IOException;
import java.util.StringTokenizer;
 
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class WordCount {
    /********** Begin **********/
	//Mapper函数
    public static class TokenizerMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        private int maxValue = 0;
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            StringTokenizer itr = new StringTokenizer(value.toString(),"\n");
            while (itr.hasMoreTokens()) {
                String[] str = itr.nextToken().split(" ");
                String name = str[0];
                one.set(Integer.parseInt(str[1]));
                word.set(name);
                context.write(word,one);
            }
            //context.write(word,one);
        }
    }
    public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();
        public void reduce(Text key, Iterable<IntWritable> values, Context context)
                throws IOException, InterruptedException {
            int maxAge = 0;
            int age = 0;
            for (IntWritable intWritable : values) {
                maxAge = Math.max(maxAge, intWritable.get());
            }
            result.set(maxAge);
            context.write(key, result);
        }
    }
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = new Job(conf, "word count");
        job.setJarByClass(WordCount.class);
        job.setMapperClass(TokenizerMapper.class);
        job.setCombinerClass(IntSumReducer.class);
        job.setReducerClass(IntSumReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        String inputfile = "/user/test/input";
        String outputFile = "/user/test/output/";
        FileInputFormat.addInputPath(job, new Path(inputfile));
        FileOutputFormat.setOutputPath(job, new Path(outputFile));
        job.waitForCompletion(true);
    /********** End **********/
    }
}

命令行

touch file01
echo Hello World Bye World
cat file01
echo Hello World Bye World >file01
cat file01
touch file02
echo Hello Hadoop Goodbye Hadoop >file02
cat file02
start-dfs.sh
hadoop fs -mkdir /usr
hadoop fs -mkdir /usr/input
hadoop fs -ls /usr/output
hadoop fs -ls /
hadoop fs -ls /usr
hadoop fs -put file01 /usr/input
hadoop fs -put file02 /usr/input
hadoop fs -ls /usr/input

第2关:文件内容合并去重

任务描述
相关知识
map类
Reducer类
Job类
编程要求
测试说明
任务描述
本关任务:使用Map/Reduce编程实现文件合并和去重操作。

相关知识
通过上一小节的学习我们了解了MapReduce大致的使用方式,本关我们来了解一下Mapper类,Reducer类和Job类。

map类
首先我们来看看Mapper对象:

在编写MapReduce程序时,要编写一个类继承Mapper类,这个Mapper类是一个泛型类型,它有四个形参类型,分别指定了map()函数的输入键,输入值,和输出键,输出值的类型。就第一关的例子来说,输入键是一个长整型,输入值是一行文本,输出键是单词,输出值是单词出现的次数。

答案代码-------------------

import java.io.IOException;

import java.util.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class Merge {

	/**
	 * @param args
	 * 对A,B两个文件进行合并,并剔除其中重复的内容,得到一个新的输出文件C
	 */
	//在这重载map函数,直接将输入中的value复制到输出数据的key上 注意在map方法中要抛出异常:throws IOException,InterruptedException
	public static class Map  extends Mapper<Object, Text, Text, Text>{
	
    /********** Begin **********/

        public void map(Object key, Text value, Context content) 
            throws IOException, InterruptedException {  
            Text text1 = new Text();
            Text text2 = new Text();
            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                text1.set(itr.nextToken());
                text2.set(itr.nextToken());
                content.write(text1, text2);
            }
        }  
	/********** End **********/
	} 
		
	//在这重载reduce函数,直接将输入中的key复制到输出数据的key上  注意在reduce方法上要抛出异常:throws IOException,InterruptedException
	public static class  Reduce extends Reducer<Text, Text, Text, Text> {
    /********** Begin **********/
        
        public void reduce(Text key, Iterable<Text> values, Context context) 
            throws IOException, InterruptedException {
            Set<String> set = new TreeSet<String>();
            for(Text tex : values){
                set.add(tex.toString());
            }
            for(String tex : set){
                context.write(key, new Text(tex));
            }
        }  
    
	/********** End **********/

	}
	
	public static void main(String[] args) throws Exception{

		// TODO Auto-generated method stub
		Configuration conf = new Configuration();
		conf.set("fs.default.name","hdfs://localhost:9000");
		
		Job job = Job.getInstance(conf,"Merge and duplicate removal");
		job.setJarByClass(Merge.class);
		job.setMapperClass(Map.class);
		job.setCombinerClass(Reduce.class);
		job.setReducerClass(Reduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		String inputPath = "/user/tmp/input/";  //在这里设置输入路径
		String outputPath = "/user/tmp/output/";  //在这里设置输出路径

		FileInputFormat.addInputPath(job, new Path(inputPath));
		FileOutputFormat.setOutputPath(job, new Path(outputPath));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}

}

第3关:信息挖掘 - 挖掘父子关系

任务描述
编程要求
测试说明
任务描述
本关任务:对给定的表格进行信息挖掘。

编程要求
你编写的程序要能挖掘父子辈关系,给出祖孙辈关系的表格。规则如下:

孙子在前,祖父在后;
输入文件路径:/user/reduce/input;
输出文件路径:/user/reduce/output。
测试说明
程序会对你编写的代码进行测试:
下面给出一个child-parent的表格,要求挖掘其中的父子辈关系,给出祖孙辈关系的表格。

输入文件内容如下:

child          parent
Steven        Lucy
Steven        Jack
Jone         Lucy
Jone         Jack
Lucy         Mary
Lucy         Frank
Jack         Alice
Jack         Jesse
David       Alice
David       Jesse
Philip       David
Philip       Alma
Mark       David
Mark       Alma

输出文件内容如下:

grand_child    grand_parent
Mark    Jesse
Mark    Alice
Philip    Jesse
Philip    Alice
Jone    Jesse
Jone    Alice
Steven    Jesse
Steven    Alice
Steven    Frank
Steven    Mary
Jone    Frank

Jone Mary
开始你的任务吧,祝你成功!

答案代码------------------------

import java.io.IOException;
import java.util.*;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class simple_data_mining {
	public static int time = 0;

	/**
	 * @param args
	 * 输入一个child-parent的表格
	 * 输出一个体现grandchild-grandparent关系的表格
	 */
	//Map将输入文件按照空格分割成child和parent,然后正序输出一次作为右表,反序输出一次作为左表,需要注意的是在输出的value中必须加上左右表区别标志
	public static class Map extends Mapper<Object, Text, Text, Text>{
		public void map(Object key, Text value, Context context) throws IOException,InterruptedException{
			/********** Begin **********/
		String line = value.toString();
             String[] childAndParent = line.split(" ");
             List<String> list = new ArrayList<>(2);
              for (String childOrParent : childAndParent) {
                 if (!"".equals(childOrParent)) {
                     list.add(childOrParent);
                  } 
              } 
              if (!"child".equals(list.get(0))) {
                  String childName = list.get(0);
                  String parentName = list.get(1);
                  String relationType = "1";
                  context.write(new Text(parentName), new Text(relationType + "+"
                        + childName + "+" + parentName));
                  relationType = "2";
                  context.write(new Text(childName), new Text(relationType + "+"
                        + childName + "+" + parentName));
              }
			/********** End **********/
		}
	}

	public static class Reduce extends Reducer<Text, Text, Text, Text>{
		public void reduce(Text key, Iterable<Text> values,Context context) throws IOException,InterruptedException{
				/********** Begin **********/

			    //输出表头
          if (time == 0) {
                context.write(new Text("grand_child"), new Text("grand_parent"));
                time++;
            }

				//获取value-list中value的child
List<String> grandChild = new ArrayList<>();

				//获取value-list中value的parent
 List<String> grandParent = new ArrayList<>();

				//左表,取出child放入grand_child
 for (Text text : values) {
                String s = text.toString();
                String[] relation = s.split("\\+");
                String relationType = relation[0];
                String childName = relation[1];
                String parentName = relation[2];
                if ("1".equals(relationType)) {
                    grandChild.add(childName);
                } else {
                    grandParent.add(parentName);
                }
            }

				//右表,取出parent放入grand_parent
 int grandParentNum = grandParent.size();
               int grandChildNum = grandChild.size();
               if (grandParentNum != 0 && grandChildNum != 0) {
                for (int m = 0; m < grandChildNum; m++) {
                    for (int n = 0; n < grandParentNum; n++) {
                        //输出结果
                    context.write(new Text(grandChild.get(m)), new Text(
                                grandParent.get(n)));
                    }
                }
            }
				/********** End **********/
		}
	}
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf,"Single table join");
		job.setJarByClass(simple_data_mining.class);
		job.setMapperClass(Map.class);
		job.setReducerClass(Reduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		String inputPath = "/user/reduce/input";   //设置输入路径
		String outputPath = "/user/reduce/output";   //设置输出路径
		FileInputFormat.addInputPath(job, new Path(inputPath));
		FileOutputFormat.setOutputPath(job, new Path(outputPath));
		System.exit(job.waitForCompletion(true) ? 0 : 1);

	}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

educoder--MapReduce基础实战各关卡通关答案 的相关文章

  • GNU Radio3.8创建OOT的详细过程(基础/C++)

    GNU Radio 学习使用 OOT 系列教程 xff1a GNU Radio3 8创建OOT的详细过程 基础 C 43 43 GNU Radio3 8创建OOT的详细过程 进阶 C 43 43 GNU Radio3 8创建OOT的详细过程
  • Johnson-Trotter(JT)算法生成排列

    对于生成 xff5b 1 xff0c xff0c n xff5d 的所有n xff01 个排列的问题 xff0c 我们可以利用减治法 xff0c 该问题的规模减一就是要生成所有 xff08 n 1 xff09 xff01 个排列 假设这个小
  • OSMWebWizard无法使用(Address family not supported by protocol)

    根据报错信息依次打开osmWebWizard py SimpleWebSocketServer py 查看对应行号的内容 xff0c 发现Simple py中有一个socket net6 可能是网络协议的问题 xff0c 查了一下 xff0
  • 粤嵌实训笔记二

    目录 20230227 20230303 xff08 第二周 xff09 main clcd clcd hbmp cbmp hgame cgame h 20230227 20230303 xff08 第二周 xff09 1 在Linux下
  • Arduino学习笔记:FreeRTOS——ESP32多任务处理

    Arduino学习笔记 xff1a FreeRTOS ESP32多任务处理 Demo span class token comment 创建任务一和任务二的句柄 xff0c 并初始化 span TaskHandle t TASK Handl
  • JAVA-信号量

    信号量 xff1a 信号量一般都有以下几个变量 xff1a count xff1a 记录可以使用的资源数wait list xff1a 等待信号量的队列 获取信号量需要判断count是否大于零 xff0c 即if count gt 0 若c
  • (程序猿专属)1024-我用代码写成浪漫情话表白你

    今天1024 xff0c 程序员节 xff01 不祝你们节日快乐了 xff0c 祝你们穿着拖鞋和裤衩去相亲吧 xff01 祝你们和甜蜜的爱情撞个满怀 xff01 一 我是你的什么啊 xff1f 你是我的bug啊 因为 xff0c 我每时每刻
  • C++中构造函数后的冒号

    C 43 43 中构造函数后的冒号 在C 43 43 中离不开类的定义 xff0c 而构造函数则是类的定义中很重要的一环 我们在构造函数中常常见到如下定义 xff1a span class token keyword class span
  • 论C语言没有输出的可能问题

    论C语言没有输出的可能问题 1 今天帮别人找bug xff0c 说是程序没有输出 题目如下 xff1a 错误代码如下 xff1a span class token macro property span class token direct
  • 【VS2019】报错:E0349没有与这些操作数匹配的运算符

    报错 xff1a E0349没有与这些操作数匹配的运算符 调试程序遇到该错误 xff0c 特此记录 span class token macro property span class token directive keyword inc
  • 基于docker技术搭建hadoop与mapreduce分布式环境

    基于docker技术搭建hadoop与mapreduce分布式环境 一 安装doker 1 宿主环境确认 如果没有的话 安装lsb relaease工具 apt install lsb release 检查版本 lsb release a
  • GNU Radio3.8创建OOT的详细过程(进阶/C++)

    GNU Radio 学习使用 OOT 系列教程 xff1a GNU Radio3 8创建OOT的详细过程 基础 C 43 43 GNU Radio3 8创建OOT的详细过程 进阶 C 43 43 GNU Radio3 8创建OOT的详细过程
  • 基于docker构建spark运行环境

    基于docker构建spark运行环境 一 安装docker与docker compose 参考之前的实验进行docker和docker compose的安装 二 系统构架图 xff1a 三 安装相关镜像 使用docker hub查找我们需
  • HDFS基本操作

    HDFS基本操作 HDFS的基本命令格式 hdfs dfs cmd lt args gt 注意 xff1a 需要事先将HADOOP HOME bin目录配置进入环境变量 列出当前目录下的文件 hdfs dfs ls 在HDFS创建文件夹 h
  • 使用mllib完成mnist手写识别任务

    使用mllib完成mnist手写识别任务 小提示 xff0c 通过restart命令重启已经退出了的容器 sudo docker restart lt contain id gt 完成识别任务准备工作 从以下网站下载数据集 MNIST手写数
  • npm install 报错 Error: EPERM: operation not permitted, rename

    报错的解决方案 原因1 xff1a 权限不足原因2 xff1a 缓存出错方法1方法2 原因3 xff1a npm版本不够原因4 xff1a 网络不稳定方法1方法2 原因5 xff1a 杀毒软件问题方法1方法2 其他 xff1a 待补充 原因
  • 马原复习知识点背诵-《马克思主义基本原理概论》

    马概复习重点 绪论 1 什么是马克思主义 1 从创造者 继承者的角度讲 马克思主义是由马克思恩格 斯创立的 而由其后各个时代 各个民族的马克思主义者 不断丰富和发展的观点和学说的体系 2 从阶级属性讲 马克思主义是无产阶级争取自身解放和整
  • 深度学习 | 三个概念:Epoch, Batch, Iteration

    转自 xff1a https www jianshu com p 22c50ded4cf7 写在前面 xff1a 在训练神经网络的时候 xff0c 我们难免会看到Batch Epoch和Iteration这几个概念 曾对这几个概念感到模糊
  • OpenStack — Nova

    文章目录 NovaNova架构Nava组件nova apinova computenova conductornova schedulernova novncproxy 创建虚拟机流程 Nova Nova是OpenStack最核心的服务模块
  • 使用Object.key和delete来将对象中值为空的属性删除。

    有些时候 xff0c 我们在接口传值时 xff0c 不需要把值为空的属性传过去 xff0c 即可使用该方法来快速的删除属性 span class token comment 深拷贝对象 xff0c 避免影响页面显示 span span cl

随机推荐

  • docker启动关闭删除所有的容器命令

    1 启动所有容器 docker start docker ps a awk 39 print 1 39 tail n 43 2 2 关闭所有容器 docker stop docker ps a awk 39 print 1 39 tail
  • GNU Radio3.8创建OOT的详细过程(python)

    GNU Radio 学习使用 OOT 系列教程 xff1a GNU Radio3 8创建OOT的详细过程 基础 C 43 43 GNU Radio3 8创建OOT的详细过程 进阶 C 43 43 GNU Radio3 8创建OOT的详细过程
  • 面试必问:从输入URL到页面展示,这中间发生了什么?(详细易懂,条理好记)

    导航流程 xff1a 从输入URL到页面展示 xff0c 这中间发生了什么 xff1f 一 进程介绍 整个过程需要各个进程之间的配合 进程与线程是两个概念 xff0c 程序启动时 xff0c 操作系统为程序创建内存 xff0c 用以存放代码
  • MATLAB神经网络工具箱函数各种图的解释

    Neural Network 该部分展示了神经网络的结构 xff0c 从结构图中可以看出该网络有三个隐含层 xff0c 神经元个数分别为9个 8个 7个 Algorithms 该部分展示了该网络所使用的训练算法 xff0c 可以看出 Dat
  • gazebo加载world模型

    使用launch文件启动gazebo加载world模型 xff0c 或者说是将world模型加入gazebo仿真器中作为环境 first xff0c 我们应该告诉gazebo 要加载的world文件放在哪里 并通过arg标签 xff0c 设
  • px4无人机报avionics power low

    px4无人机报avionics power low xff0c 将无人机连接qgc中 xff0c 将CBRK SUPPLY参数设为最大值即可
  • QGC地面站PC桥接px4(QGC+wifi+机载计算机+px4)

    QGC地面站PC桥接px4 xff08 QGC 43 wifi 43 机载计算机 43 px4 xff09 1 在机载计算机上安装ubuntu2 安装ros3 机载计算机上安装mavros1安装mavros2 安装安装mavros相关的 g
  • 消除Gazebo模型抖动

    自己创建的模型导入到gazebo中往往会不停的跳动 xff0c 一般是由于转动惯量设置不正确导致的 xff0c 可以将转动惯量注释掉 如果注释点后还是有这种情况 xff0c 需要设置非零的min depth xff0c 模型通常会稳定 将其
  • px4报dangerously low battery! shutting system down.

    这两天用px4突然开始报dangerously low battery shutting system down xff0c 从px4 github项目上看到是因为telem接口中的tx和rx相连了 xff0c mavlink的消息从px4
  • realsense t265测试中的一些小问题

    realsense t265测试中出现的一些小问题 环境 xff1a Ubuntu18 04 内核 xff1a 5 4 官方教程 xff1a https github com IntelRealSense realsense ros 测试过
  • 查看T265配置信息及参数

    查看T265配置信息及参数 1 验证SDK安装成功 安装完sdk后 xff0c 终端里运行 realsense viewer 查看相机输出的图像和imu信息 xff0c 可以验证sdk是否安装成功 2 查看T265配置信息 rs enume
  • 修改vins-fusion中T265的相机模型文件

    修改vins fusion中T265的相机模型文件 在使用T265跑vins fusion的过程中 xff0c 首先需要设置相机相关的配置文件 xff0c 网上给出的相关测试教程都没有很明白的说明这一部分 xff0c 都将T265作为了ME
  • GNU Radio3.8:创建自定义的QPSK块(C++)

    GNU Radio 学习使用 OOT 系列教程 xff1a GNU Radio3 8创建OOT的详细过程 基础 C 43 43 GNU Radio3 8创建OOT的详细过程 进阶 C 43 43 GNU Radio3 8创建OOT的详细过程
  • NUC主机部署px4+T265

    NUC主机部署px4 43 T265 安装T265驱动及realsense ros安装mavros安装VIO测试 px4使用T265做视觉定位在官方指导手册上给出了相关的教程 xff0c 但有些细节部分比较蛋疼 xff0c 需要修改 xff
  • 安装evo出现import any qt binding错误

    安装evo出现error Failed to import any qt binding 需要测评无人机轨迹精度 xff0c 使用evo工具 xff0c 安装可以参考github上给出的流程 xff0c 我选的是从源文件安装 xff0c 在
  • rosbag2csv

    1 record bag rosbag record O topic name group 2 rosbag to csv rostopic echo b bag name bag p topic name gt csv name csv
  • ubuntu18.04使用anaconda3配置yolov5

    ubuntu18 04使用anaconda3配置yolov5 1 anaconda官网下载相关的sh文件 在sh文件所在的文件夹里打开终端 使用bash命令 运行sh文件安装anaconda 在安装的过程中首先有一个确定anaconda的安
  • 无人机仿真搭建:ROS,Gazebo,SITL,MAVROS,PX4

    写在前面 最近一直在搭建无人机仿真的环境 xff0c 系统都卸载安装了很多次才安装好 xff0c 所以写下这篇博客来记录一下 xff0c 万一以后还要再搭也可以有个参考 xff0c 也可以给大家做个参考 这个是结合我自己系统来安装的 xff
  • C++ 类的构造函数之冒号初始化语法

    在实现类的时候往往需要写一个构造函数用于初始化对象 xff0c 出去一般的函数语法之外 xff0c 还有一种冒号语法 比如 xff0c 下面两种构造函数的写法近似相同 xff1a 常规方法 class A private int index
  • educoder--MapReduce基础实战各关卡通关答案

    第1关 xff1a 成绩统计 任务描述 相关知识 什么是MapReduce 如何使用MapReduce进行运算 代码解释 编程要求 测试说明 任务描述 本关任务 xff1a 使用Map Reduce计算班级中年龄最大的学生 相关知识 为了完