Newer
Older
//UNCOMMENT//Map<Integer, List<String>> result = null; // TODO
Stuart Marks
committed
//BEGINREMOVE
Map<Integer, Set<String>> result =
input.entrySet().stream()
.flatMap(e -> e.getValue().stream()
.map(v -> new SimpleEntry<>(e.getKey(), v)))
.collect(groupingBy(Entry::getValue, mapping(Entry::getKey, toSet())));
Stuart Marks
committed
//ENDREMOVE
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
assertEquals(new HashSet<>(Arrays.asList("a", "c", "d")), result.get(1));
assertEquals(new HashSet<>(Arrays.asList("a", "b", "e")), result.get(2));
assertEquals(new HashSet<>(Arrays.asList("b", "c", "f")), result.get(3));
assertEquals(new HashSet<>(Arrays.asList("d", "e", "f")), result.get(4));
assertEquals(4, result.size());
}
/**
* Select from the input list each word that longer than the immediately
* preceding word. Include the first word, since it is longer than the
* (nonexistent) word that precedes it.
*
* XXX - compare to ex11
*/
@Test
public void ex28_selectLongerThanPreceding() {
List<String> input = Arrays.asList(
"alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel");
//UNCOMMENT//List<String> result = null; // TODO
Stuart Marks
committed
//BEGINREMOVE
List<String> result =
IntStream.range(0, input.size())
.filter(pos -> pos == 0 || input.get(pos-1).length() < input.get(pos).length())
.mapToObj(pos -> input.get(pos))
.collect(toList());
Stuart Marks
committed
//ENDREMOVE
assertEquals("[alfa, bravo, charlie, foxtrot, hotel]", result.toString());
Stuart Marks
committed
}
Stuart Marks
committed
// <editor-fold defaultstate="collapsed">
// Instead of a stream of words (Strings), run an IntStream of positions.
Stuart Marks
committed
// </editor-fold>
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
/**
* Generate a list of words that is the concatenation of each adjacent
* pair of words in the input list. For example, if the input is
* [x, y, z]
* the output should be
* [xy, yz]
*
* XXX - compare to ex11
*/
@Test
public void ex29_concatenateAdjacent() {
List<String> input = Arrays.asList(
"alfa", "bravo", "charlie", "delta", "echo", "foxtrot");
//UNCOMMENT//List<String> result = null; // TODO
//BEGINREMOVE
List<String> result =
IntStream.range(1, input.size())
.mapToObj(pos -> input.get(pos-1) + input.get(pos))
.collect(toList());
//ENDREMOVE
assertEquals("[alfabravo, bravocharlie, charliedelta, deltaecho, echofoxtrot]",
result.toString());
}
// Hint:
Stuart Marks
committed
// <editor-fold defaultstate="collapsed">
// Instead of a stream of words (Strings), run an IntStream of positions.
Stuart Marks
committed
// </editor-fold>
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
/**
* Select the longest words from the input list. That is, select the words
* whose lengths are equal to the maximum word length. For this exercise,
* it's easiest to perform two passes over the input list.
*
* XXX - compare to ex09 and ex10
*/
@Test
public void ex30_selectLongestWords() {
List<String> input = Arrays.asList(
"alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel");
//UNCOMMENT//List<String> result = null; // TODO
//BEGINREMOVE
int max = input.stream()
.mapToInt(String::length)
.max()
.getAsInt();
List<String> result = input.stream()
.filter(s -> s.length() == max)
.collect(toList());
//ENDREMOVE
assertEquals("[charlie, foxtrot]", result.toString());
}
/**
* Select the longest words from the input stream. That is, select the words
* whose lengths are equal to the maximum word length. For this exercise,
* you must compute the result in a single pass over the input stream.
*
* XXX - compare to ex30
*/
@Test
public void ex31_selectLongestWordsOnePass() {
Stream<String> input = Stream.of(
"alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel");
//UNCOMMENT//List<String> result = null; // TODO
//BEGINREMOVE
List<String> result = new ArrayList<>();
input.forEachOrdered(s -> {
if (result.isEmpty()) {
result.add(s);
} else {
int reslen = result.get(0).length();
int curlen = s.length();
if (curlen > reslen) {
result.clear();
result.add(s);
} else if (curlen == reslen) {
result.add(s);
}
}
});
//ENDREMOVE
assertEquals("[charlie, foxtrot]", result.toString());
}
/**
* Create a list of non-overlapping sublists of the input list, where each
* sublist (except for the first one) starts with a word whose first character is a ":".
* For example, given the input list
* [w, x, :y, z]
* the output should be
* [[w, x], [:y, z]]
*/
@Test
public void ex32_partitionIntoSublists() {
List<String> input = Arrays.asList(
"alfa", "bravo", ":charlie", "delta", ":echo", ":foxtrot", "golf", "hotel");
//UNCOMMENT//List<List<String>> result = null; // TODO
//BEGINREMOVE
List<Integer> bounds =
IntStream.rangeClosed(0, input.size())
.filter(i -> i == 0 || i == input.size() || input.get(i).startsWith(":"))
.boxed()
.collect(toList());
List<List<String>> result =
IntStream.range(1, bounds.size())
.mapToObj(i -> input.subList(bounds.get(i-1), bounds.get(i)))
.collect(toList());
//ENDREMOVE
assertEquals("[[alfa, bravo], [:charlie, delta], [:echo], [:foxtrot, golf, hotel]]",
result.toString());
}
/**
* Given a stream of integers, compute separate sums of the even and odd values
* in this stream. Since the input is a stream, this necessitates making a single
* pass over the input.
*/
@Test
public void ex33_separateOddEvenSums() {
IntStream input = new Random(987523).ints(20, 0, 100);
//UNCOMMENT//int sumEvens = 0; // TODO
//UNCOMMENT//int sumOdds = 0; // TODO
//BEGINREMOVE
Map<Boolean, Integer> sums =
input.boxed()
.collect(partitioningBy(i -> (i & 1) == 1, Collectors.summingInt(i -> i)));
int sumEvens = sums.get(false);
int sumOdds = sums.get(true);
//ENDREMOVE
assertEquals(516, sumEvens);
assertEquals(614, sumOdds);
}
// Hint:
Stuart Marks
committed
// <editor-fold defaultstate="collapsed">
// Use Collectors.partitioningBy().
Stuart Marks
committed
// </editor-fold>
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
/**
* Given a string, split it into a list of strings consisting of
* consecutive characters from the original string. Note: this is
* similar to Python's itertools.groupby function, but it differs
* from Java's Collectors.groupingBy() collector.
*
* XXX - compare to ex32
*/
@Test
public void ex34_splitCharacterRuns() {
String input = "aaaaabbccccdeeeeeeaaafff";
//UNCOMMENT//List<String> result = null; // TODO
//BEGINREMOVE
List<Integer> bounds =
IntStream.rangeClosed(0, input.length())
.filter(i -> i == 0 || i == input.length() ||
input.charAt(i-1) != input.charAt(i))
.boxed()
.collect(toList());
List<String> result =
IntStream.range(1, bounds.size())
.mapToObj(i -> input.substring(bounds.get(i-1), bounds.get(i)))
.collect(toList());
//ENDREMOVE
assertEquals("[aaaaa, bb, cccc, d, eeeeee, aaa, fff]", result.toString());
}
/**
* Given a string, find the substring containing the longest run of consecutive,
* equal characters.
*
* XXX - compare to ex34
*/
@Test
public void ex35_longestCharacterRuns() {
String input = "aaaaabbccccdeeeeeeaaafff";
//UNCOMMENT//String result = null; // TODO
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
//BEGINREMOVE
List<Integer> bounds =
IntStream.rangeClosed(0, input.length())
.filter(i -> i == 0 || i == input.length() ||
input.charAt(i-1) != input.charAt(i))
.boxed()
.collect(toList());
String result =
IntStream.range(1, bounds.size())
.boxed()
.max((i, j) -> Integer.compare(bounds.get(i) - bounds.get(i-1),
bounds.get(j) - bounds.get(j-1)))
.map(i -> input.substring(bounds.get(i-1), bounds.get(i)))
.get();
//ENDREMOVE
assertEquals("eeeeee", result);
}
/**
* Given a parallel stream of strings, collect them into a collection in reverse order.
* Since the stream is parallel, you MUST write a proper combiner function in order to get
* the correct result.
*/
@Test
public void ex36_reversingCollector() {
Stream<String> input =
IntStream.range(0, 100).mapToObj(String::valueOf).parallel();
//UNCOMMENT//Collection<String> result =
//UNCOMMENT// input.collect(Collector.of(null, null, null)); // TODO
//BEGINREMOVE
Collection<String> result =
input.collect(Collector.of(ArrayDeque::new,
ArrayDeque::addFirst,
(d1, d2) -> { d2.addAll(d1); return d2; }));
//ENDREMOVE
assertEquals(
IntStream.range(0, 100)
.map(i -> 99 - i)
.mapToObj(String::valueOf)
.collect(Collectors.toList()),
new ArrayList<>(result));
}
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
/**
* Given an array of int, find the int value that occurs a majority
* of times in the array (that is, strictly more than half of the
* elements are that value), and return it in an OptionalInt. If there
* is no majority value, return an empty OptionalInt.
*/
OptionalInt majority(int[] array) {
//UNCOMMENT//return null; // TODO
//BEGINREMOVE
Map<Integer, Long> map =
Arrays.stream(array)
.boxed()
.collect(groupingBy(x -> x, counting()));
return map.entrySet().stream()
.filter(e -> e.getValue() > array.length / 2)
.mapToInt(Entry::getKey)
.findAny();
//ENDREMOVE
}
@Test
public void ex37_majority() {
int[] array1 = { 3, 3, 4, 2, 4, 4, 2, 4, 4 };
int[] array2 = { 3, 3, 4, 2, 4, 4, 2, 4 };
OptionalInt result1 = majority(array1);
OptionalInt result2 = majority(array2);
assertTrue(result1.isPresent() && result1.getAsInt() == 4);
assertFalse(result2.isPresent());
}
// ========================================================
// END OF EXERCISES -- CONGRATULATIONS!
// TEST INFRASTRUCTURE IS BELOW
// ========================================================
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
static final String REGEXP = "[- .:,]+"; // for splitting into words
private BufferedReader reader;
@Before
public void z_setUpBufferedReader() throws IOException {
reader = Files.newBufferedReader(
Paths.get("SonnetI.txt"), StandardCharsets.UTF_8);
}
@After
public void z_closeBufferedReader() throws IOException {
reader.close();
}
}
//BEGINREMOVE
/*
* Procedure for deriving exercise file from answers.
* - Open a shell and change do the LambdaLab/test/solutions directory.
* - Run the "cleanit" perl script from within this directory.
* - This should generate the LambdaLab/test/exercises/Exercises.java file automatically.
* - Make sure the only files open in the project are (unsolved!) Exercises.java and
* SonnetI.txt, then run clean, and close the NB project.
*/
//ENDREMOVE