forked from alexprut/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
90 lines (70 loc) · 2.36 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
import java.util.*;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
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++) {
JSONObject record = (JSONObject) inputdata.get(i);
mapper(record);
}
Iterator it = intermediate.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
reducer((int) pair.getKey(), (ArrayList) pair.getValue());
it.remove();
}
return finalResult;
}
private void emit(LinkedHashMap obj) {
finalResult.put(resultCount++, obj);
}
private <T> void reducer(T key, ArrayList value) {
LinkedHashMap obj = new LinkedHashMap();
obj.put("key", key);
obj.put("value", key);
emit(obj);
}
private void mapper(JSONObject record) {
int value = (int) record.get("value");
if (value > 10 && value % 2 != 0) {
emitIntermediate(value, 1);
}
}
private <T1, T2> void emitIntermediate(T1 key, T2 value) {
if (!intermediate.containsKey(key))
intermediate.put(key, new ArrayList());
ArrayList temp = (ArrayList) 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 t = sc.nextInt();
int linecount = 0;
for (int i = 0; i < t; i++) {
int value = sc.nextInt();
Map obj = new JSONObject();
obj.put("key", linecount);
obj.put("value", value);
inputdata.put(linecount++, obj);
}
MapReduce mapred = new MapReduce();
JSONObject result = mapred.execute(inputdata);
for (int i = 0; i < result.size(); i++) {
LinkedHashMap record = (LinkedHashMap) result.get(i);
int value = (int) record.get("value");
System.out.println(value);
}
}
}