-
Notifications
You must be signed in to change notification settings - Fork 2
/
Mixing.java
100 lines (83 loc) · 2.8 KB
/
Mixing.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
import java.util.*;
public class Mixing {
public static String mix(String s1, String s2) {
// take in two strings
// find the counts of each lowercase letter
// get teh maximum count of that letter and what string it came from
// construct a string consisting of the maxiumums sorted by max then sorted by lex order
Map<Character, Integer> map1 = getCounts(s1);
Map<Character, Integer> map2 = getCounts(s2);
List<MixHelper> mixes = new ArrayList<>();
fillHelperFromMap(map1, map2, mixes, '1');
fillHelperFromMap(map2, map1, mixes, '2');
Collections.sort(mixes, new Comparator<MixHelper>() {
public int compare(MixHelper mh1, MixHelper mh2) {
if (mh1.count == mh2.count) {
if (mh1.sourceString == mh2.sourceString) {
return mh1.c - mh2.c;
} else {
return mh1.sourceString - mh2.sourceString;
}
} else {
return mh2.count - mh1.count;
}
}
});
List<String> mixStrings = new ArrayList<String>();
for (MixHelper mh: mixes) {
mixStrings.add(mh.toString());
}
return String.join("/", mixStrings);
}
public static void fillHelperFromMap(Map<Character, Integer> map1, Map<Character, Integer> map2, List<MixHelper> mixes, char defaultSource) {
for (Iterator<Map.Entry<Character, Integer>> i1 = map1.entrySet().iterator(); i1.hasNext();) {
Map.Entry<Character, Integer> e1 = i1.next();
int count = e1.getValue();
char c = e1.getKey();
char sourceString = defaultSource;
if (count > 1) { // if not ignore everything
if (map2.containsKey(c)) {
if (map2.get(c) == count) {
sourceString = '=';
} else if (map2.get(c) > count) {
sourceString = defaultSource == '1' ? '2' : '1';
count = map2.get(c);
}
}
mixes.add(new MixHelper(sourceString, c, count));
i1.remove();
map2.remove(c);
}
}
}
public static Map<Character, Integer> getCounts(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
if (c >= 'a' && c <= 'z') {
if (!map.containsKey(c)) {
map.put(c, 0);
}
map.put(c, map.get(c) + 1);
}
}
return map;
}
}
class MixHelper {
Character sourceString;
Character c;
Integer count;
public MixHelper(Character sourceString, Character c, Integer count) {
this.sourceString = sourceString;
this.c = c;
this.count = count;
}
@Override
public String toString() {
String chars = "";
for (int i = 0; i < count; i++) {
chars += c + "";
}
return sourceString + ":" + chars;
}
}