大數據學習之十一——MapReduce代碼實例:平面距離

***座標距離***app

場景描述:orm

已知一個單身美女的座標,和一羣單身帥哥的座標,求離美女最近的帥哥blog

數據(空格分開x、y座標): (10,12)(23,23)(20,20)(1,3)(23,7)token

假設美女的座標爲(5,5)get

代碼實現:input

public class distance2 {     it

static String INPUT_PATH="hdfs://master:9000/input/h.txt";  io

static String OUTPUT_PATH="hdfs://master:9000/output/distance2";    table

static class MyMapper extends Mapper<Object,Object,DoubleWritable,Text>{    //距離做爲double類型,輸出格式控制ast

DoubleWritable output_key=new DoubleWritable();   

DoubleWritable output_value=new DoubleWritable();   

DoubleWritable out_distance=new DoubleWritable();   

Text record=new Text();   //輸出格式的控制

protected void map(Object key, Object value, Context context) throws IOException, InterruptedException{    

String[] tokens=value.toString().split(",",2);     //按照,分隔開

output_key.set(Double.parseDouble(tokens[0]));    //第一列給座標x

output_value.set(Double.parseDouble(tokens[1]));    //第二列給座標y

double x1=output_key.get()-5;    //平面距離公式

double y1=output_value.get()-5;    

double x=output_key.get();    

double y=output_value.get();        

String rec="x:"+x+","+"y:"+y;            //輸出格式

out_distance.set(Math.sqrt(Math.pow(x1, 2)+Math.pow(y1, 2)));   

 record.set(rec);    

context.write(out_distance, record);   

}  

}  

 static class MyReduce extends Reducer<DoubleWritable,Text,DoubleWritable,Text>{   

DoubleWritable output_key=new DoubleWritable();  

 DoubleWritable output_value=new DoubleWritable();    

protected void reduce(DoubleWritable key,Iterable<Text> values,Context context) throws IOException,InterruptedException{    

while(values.iterator().hasNext()){       //循環寫入

context.write(key,values.iterator().next());   

 }   

 }    

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

Path outputpath=new Path(OUTPUT_PATH);   

Configuration conf=new Configuration();      

Job job=Job.getInstance(conf);   

FileInputFormat.setInputPaths(job, INPUT_PATH);  

 FileOutputFormat.setOutputPath(job,outputpath);     

 job.setMapperClass(MyMapper.class);   

job.setReducerClass(MyReduce.class);     

 job.setOutputKeyClass(DoubleWritable.class);  

 job.setOutputValueClass(Text.class);      

job.waitForCompletion(true);  

}

}

相關文章
相關標籤/搜索