-
Notifications
You must be signed in to change notification settings - Fork 138
/
Solution.java
111 lines (95 loc) Β· 2.49 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import java.util.*;
import org.json.simple.JSONObject;
class MapReduce
{
private LinkedHashMap intermediate;
private JSONObject finalResult = new JSONObject();
private int resultCount;
MapReduce()
{
resultCount=0;
finalResult = new JSONObject();
intermediate=new LinkedHashMap();
}
JSONObject execute(JSONObject inputdata)
{
for(int i=0;i<inputdata.size();i++)
{
LinkedHashMap record=(LinkedHashMap)inputdata.get(i);
mapper(record);
}
Iterator it = intermediate.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
reducer((int)pair.getKey(), (HashSet)pair.getValue());
it.remove();
}
return finalResult;
}
private void emit(LinkedHashMap obj)
{
finalResult.put(resultCount++,obj);
}
private void reducer(int key, HashSet value)
{
// Fill up the question mark in the reducer function!
if(value.size()==2)
{
LinkedHashMap obj=new LinkedHashMap();
obj.put("key",key);
emit(obj);
}
}
private void mapper(LinkedHashMap record)
{
String value=(String)record.get("value");
int key=(int)record.get("key");
emitIntermediate(key,value);
}
private void emitIntermediate(int key, String value)
{
if(!intermediate.containsKey(key))
intermediate.put(key,new HashSet());
HashSet temp=(HashSet)intermediate.get(key);
temp.add(value);
intermediate.put(key,temp);
}
}
public class Main
{
public static void main(String []argh)
{
JSONObject inputdata= new JSONObject();
Scanner sc=new Scanner(System.in);
int Nr=sc.nextInt();
int Ns=sc.nextInt();
int []R=new int[Nr];
int []S=new int[Ns];
int c=0;
for(int i=0;i<Nr;i++)
{
Map obj=new LinkedHashMap();
R[i]=sc.nextInt();
obj.put("value","R");
obj.put("key",R[i]);
inputdata.put(c,obj);
c++;
}
for(int i=0;i<Ns;i++)
{
Map obj=new LinkedHashMap();
S[i]=sc.nextInt();
obj.put("value","S");
obj.put("key",S[i]);
inputdata.put(c,obj);
c++;
}
MapReduce mapred= new MapReduce();
JSONObject result=mapred.execute(inputdata);
for(int i=0;i<result.size();i++)
{
LinkedHashMap record=(LinkedHashMap)result.get(i);
System.out.println(record.get("key"));
}
}
}