- Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathFirstBatch.java
More file actions
Latest commit
375 lines (342 loc) · 15.2 KB
/
Copy pathFirstBatch.java
File metadata and controls
375 lines (342 loc) · 15.2 KB
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
importjava.util.Arrays;
importjava.util.function.IntPredicate;
importjava.util.stream.IntStream;
/**
* A first batch of array algorithms demonstrating loops, two-pointer
* techniques, and functional predicates.
* <p>
* Updated for Java 21+ with {@link IntPredicate} for flexible filtering,
* streams where they improve clarity, and better naming throughout.
*
* @author Ilkka Kokkarinen
*/
publicclassFirstBatch {
// -----------------------------------------------------------------------
// Counting and collecting elements that satisfy a predicate.
// Demonstrates: IntPredicate (functional interface), higher-order methods.
//
// The old version hardcoded an "isFunny" test. The modern version accepts
// any IntPredicate, so callers choose the criterion:
//
// countMatching(a, n -> n % 3 == 0) // divisible by 3
// countMatching(a, n -> isPrime(n)) // primes
// countMatching(a, FirstBatch::isPrime) // same, method reference
// -----------------------------------------------------------------------
/**
* Count how many elements in the array satisfy the given predicate.
*
* @param values the array to examine
* @param predicate the condition to test each element against
* @return the count of matching elements
*/
publicstaticintcountMatching(int[] values, IntPredicatepredicate) {
intcount = 0;
for (intvalue : values) {
if (predicate.test(value)) { count++; }
}
returncount;
}
/**
* Collect all elements satisfying the predicate into a new array.
*
* @param values the array to filter
* @param predicate the condition to test each element against
* @return a new array containing only the matching elements, in order
*/
publicstaticint[] collectMatching(int[] values, IntPredicatepredicate) {
// With streams, this is a clean one-liner. Under the hood it does
// essentially the same two-pass (or buffer-and-trim) work.
returnArrays.stream(values)
.filter(predicate)
.toArray();
}
// A sample predicate for demonstration purposes.
publicstaticbooleanisDivisibleByThree(intn) {
returnn % 3 == 0;
}
// -----------------------------------------------------------------------
// Selection sort — our first (and worst) sorting algorithm.
// Demonstrates: nested loops, in-place swapping, finding a minimum.
// -----------------------------------------------------------------------
/**
* Find the index of the smallest element in {@code array[from..to]}
* (inclusive on both ends).
*/
privatestaticintindexOfMinimum(int[] array, intfrom, intto) {
intminIndex = from;
for (inti = from + 1; i <= to; i++) {
if (array[i] < array[minIndex]) { minIndex = i; }
}
returnminIndex;
}
/**
* Sort the array in place using selection sort. Time complexity is
* O(n²) regardless of input — there are far better algorithms, but
* this one is easy to understand and prove correct.
*
* @param array the array to sort
*/
publicstaticvoidselectionSort(int[] array) {
for (inti = 0; i < array.length - 1; i++) {
intminIndex = indexOfMinimum(array, i, array.length - 1);
// Swap array[i] with the smallest remaining element.
inttemp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
// -----------------------------------------------------------------------
// Three two-pointer array algorithms of similar spirit.
// Each walks through one or two sorted arrays in a single pass.
// -----------------------------------------------------------------------
/**
* Interleave elements of two arrays: take one from {@code first}, one
* from {@code second}, alternating. When one runs out, append the rest
* of the other. (This is sometimes called a "riffle" or "zip".)
*
* @param first the first array
* @param second the second array
* @return the interleaved result
*/
publicstaticint[] zip(int[] first, int[] second) {
varresult = newint[first.length + second.length];
inti = 0, dest = 0;
while (i < first.length && i < second.length) {
result[dest++] = first[i];
result[dest++] = second[i];
i++;
}
while (i < first.length) { result[dest++] = first[i++]; }
while (i < second.length) { result[dest++] = second[i++]; }
returnresult;
}
/**
* Merge two sorted arrays into one sorted array. Both inputs must
* already be sorted in ascending order. This is the key subroutine
* of merge sort.
*
* @param first the first sorted array
* @param second the second sorted array
* @return a new sorted array containing all elements of both inputs
*/
publicstaticint[] merge(int[] first, int[] second) {
varresult = newint[first.length + second.length];
inti = 0, j = 0, dest = 0;
while (i < first.length && j < second.length) {
if (first[i] <= second[j]) { result[dest++] = first[i++]; }
else { result[dest++] = second[j++]; }
}
while (i < first.length) { result[dest++] = first[i++]; }
while (j < second.length) { result[dest++] = second[j++]; }
returnresult;
}
/**
* Compute the intersection of two sorted arrays — elements that appear
* in both. Both inputs must be sorted in ascending order. The result
* preserves duplicates only if they appear in both arrays.
*
* @param first the first sorted array
* @param second the second sorted array
* @return a new sorted array of common elements
*/
publicstaticint[] intersection(int[] first, int[] second) {
// IntStream.Builder avoids the two-pass approach (count then fill)
// and the boxing overhead of ArrayList<Integer>.
varbuilder = IntStream.builder();
inti = 0, j = 0;
while (i < first.length && j < second.length) {
if (first[i] < second[j]) { i++; }
elseif (first[i] > second[j]) { j++; }
else {
builder.add(first[i]);
i++;
j++;
}
}
returnbuilder.build().toArray();
}
// -----------------------------------------------------------------------
// Remove consecutive duplicates from a sorted array.
// -----------------------------------------------------------------------
/**
* Return a new array with consecutive duplicates removed. The input
* must be sorted so that equal elements are adjacent.
*
* @param sorted the sorted input array
* @return a new array with duplicates removed
*/
publicstaticint[] removeDuplicates(int[] sorted) {
if (sorted.length == 0) { returnsorted; }
// IntStream with a stateful filter is one option, but the explicit
// approach is clearer and avoids concerns about stream ordering.
// Single pass: write each element that differs from its predecessor.
varresult = newint[sorted.length]; // upper bound on size
result[0] = sorted[0];
intdest = 1;
for (inti = 1; i < sorted.length; i++) {
if (sorted[i] != sorted[i - 1]) {
result[dest++] = sorted[i];
}
}
returnArrays.copyOf(result, dest);
}
// -----------------------------------------------------------------------
// Longest ascending run — a one-pass algorithm with state variables.
// -----------------------------------------------------------------------
/**
* Find the length of the longest strictly ascending run in the array.
* Demonstrates the pattern of maintaining "current" and "best so far"
* state variables that are updated at each step.
*
* @param values the array to examine
* @return the length of the longest ascending run (at least 1 if non-empty)
*/
publicstaticintlongestAscending(int[] values) {
if (values.length == 0) { return0; }
intcurrentRun = 1;
intlongestRun = 1;
for (inti = 1; i < values.length; i++) {
if (values[i] > values[i - 1]) {
currentRun++;
if (currentRun > longestRun) { longestRun = currentRun; }
} else {
currentRun = 1;
}
}
returnlongestRun;
}
// -----------------------------------------------------------------------
// Roman numeral encoding and decoding.
// -----------------------------------------------------------------------
// Parallel arrays: each Roman symbol paired with its decimal value.
// Ordered from largest to smallest for the greedy encoding algorithm.
privatestaticfinalString[] ROMAN_SYMBOLS = {
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
};
privatestaticfinalint[] ROMAN_VALUES = {
1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
};
/**
* Encode a positive integer as a Roman numeral string.
* Uses a greedy algorithm: repeatedly subtract the largest possible
* Roman value and append its symbol.
*
* @param number the positive integer to encode (must be ≥ 1)
* @return the Roman numeral representation
* @throws IllegalArgumentException if number is less than 1
*/
publicstaticStringromanEncode(intnumber) {
if (number < 1) {
thrownewIllegalArgumentException("Cannot convert " + number + " to Roman");
}
varresult = newStringBuilder();
intsymbolIndex = 0;
while (number > 0) {
while (number >= ROMAN_VALUES[symbolIndex]) {
result.append(ROMAN_SYMBOLS[symbolIndex]);
number -= ROMAN_VALUES[symbolIndex];
}
symbolIndex++;
}
returnresult.toString();
}
// For decoding, we only need the seven basic symbols and their values.
privatestaticfinalStringBASIC_SYMBOLS = "MDCLXVI";
privatestaticfinalint[] BASIC_VALUES = {1000, 500, 100, 50, 10, 5, 1};
/**
* Decode a Roman numeral string to its integer value. Reads right to left:
* if a symbol's value is less than the previous one, it is subtracted
* (this handles cases like IV = 4 and IX = 9).
*
* @param roman the Roman numeral string (case-insensitive)
* @return the decoded integer value
* @throws IllegalArgumentException if the string contains invalid characters
*/
publicstaticintromanDecode(Stringroman) {
roman = roman.toUpperCase();
intresult = 0;
intpreviousValue = 0;
// Process right to left so we can detect subtractive notation.
for (inti = roman.length() - 1; i >= 0; i--) {
intsymbolIndex = BASIC_SYMBOLS.indexOf(roman.charAt(i));
if (symbolIndex == -1) {
thrownewIllegalArgumentException(
"Illegal Roman numeral character: " + roman.charAt(i));
}
intcurrentValue = BASIC_VALUES[symbolIndex];
// Subtractive rule: IV means 5 - 1, not 5 + 1.
result += (currentValue < previousValue) ? -currentValue : currentValue;
previousValue = currentValue;
}
returnresult;
}
/**
* Verify that encoding and decoding are perfect inverses for 1..4999.
*/
publicstaticbooleantestRomanConversions() {
returnIntStream.rangeClosed(1, 4999)
.allMatch(n -> romanDecode(romanEncode(n)) == n);
}
// -----------------------------------------------------------------------
// Main method — exercise each example and display results.
// -----------------------------------------------------------------------
publicstaticvoidmain(String[] args) {
// --- Predicate-based counting and collecting ---
System.out.println("--- countMatching / collectMatching ---");
int[] data = {3, 7, 9, 12, 15, 20, 21, 25, 30};
System.out.printf("Data: %s%n", Arrays.toString(data));
// Pass different predicates to the same method:
IntPredicatedivBy3 = FirstBatch::isDivisibleByThree;
IntPredicateisEven = n -> n % 2 == 0;
IntPredicateover15 = n -> n > 15;
System.out.printf("Divisible by 3: count=%d, values=%s%n",
countMatching(data, divBy3), Arrays.toString(collectMatching(data, divBy3)));
System.out.printf("Even: count=%d, values=%s%n",
countMatching(data, isEven), Arrays.toString(collectMatching(data, isEven)));
System.out.printf("Greater than 15: count=%d, values=%s%n",
countMatching(data, over15), Arrays.toString(collectMatching(data, over15)));
// Predicates can also be composed with and/or/negate:
IntPredicatedivBy3AndEven = divBy3.and(isEven);
System.out.printf("Div by 3 AND even: %s%n%n",
Arrays.toString(collectMatching(data, divBy3AndEven)));
// --- Selection sort ---
System.out.println("--- selectionSort ---");
int[] unsorted = {38, 27, 43, 3, 9, 82, 10};
System.out.printf("Before: %s%n", Arrays.toString(unsorted));
selectionSort(unsorted);
System.out.printf("After: %s%n%n", Arrays.toString(unsorted));
// --- Zip, merge, intersection ---
System.out.println("--- zip / merge / intersection ---");
int[] left = {1, 3, 5, 7, 9};
int[] right = {2, 4, 6};
System.out.printf("zip(%s, %s) = %s%n",
Arrays.toString(left), Arrays.toString(right),
Arrays.toString(zip(left, right)));
System.out.printf("merge(%s, %s) = %s%n",
Arrays.toString(left), Arrays.toString(right),
Arrays.toString(merge(left, right)));
int[] sorted1 = {1, 3, 5, 7, 9, 11};
int[] sorted2 = {2, 3, 5, 8, 9, 13};
System.out.printf("intersection(%s, %s) = %s%n%n",
Arrays.toString(sorted1), Arrays.toString(sorted2),
Arrays.toString(intersection(sorted1, sorted2)));
// --- Remove duplicates ---
System.out.println("--- removeDuplicates ---");
int[] withDups = {1, 1, 2, 3, 3, 3, 4, 5, 5};
System.out.printf("removeDuplicates(%s) = %s%n%n",
Arrays.toString(withDups), Arrays.toString(removeDuplicates(withDups)));
// --- Longest ascending run ---
System.out.println("--- longestAscending ---");
int[] sequence = {3, 5, 7, 2, 4, 6, 8, 10, 1};
System.out.printf("longestAscending(%s) = %d%n%n",
Arrays.toString(sequence), longestAscending(sequence));
// --- Roman numerals ---
System.out.println("--- Roman numerals ---");
for (intn : newint[]{1, 4, 9, 42, 1999, 2025, 3888}) {
Stringroman = romanEncode(n);
intdecoded = romanDecode(roman);
System.out.printf("%4d → %-15s → %d%n", n, roman, decoded);
}
System.out.printf("%nRoundtrip test (1..4999): %s%n", testRomanConversions());
}
}