-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathCompression.java
384 lines (319 loc) · 11.1 KB
/
Compression.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
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
376
377
378
379
380
381
382
383
384
package compression;
import java.util.Arrays;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* @author peter.levart (at) gmail.com
* @author ales.justin (at) gmail.com
*/
public class Compression {
// using IntStream.reduce
public static String compress1(String input) {
return compress1(input.chars());
}
public static String compress1parallel(String input) {
return compress1(input.chars().parallel());
}
private static String compress1(IntStream chars) {
var countCharArray = chars
.mapToObj(c -> new int[]{1, c})
.reduce((nc1, nc2) -> {
if (nc1[nc1.length - 1] == nc2[1]) {
var ncr = Arrays.copyOf(nc1, nc1.length + nc2.length - 2);
ncr[nc1.length - 2] += nc2[0];
System.arraycopy(nc2, 2, ncr, nc1.length, nc2.length - 2);
return ncr;
} else {
var ncr = Arrays.copyOf(nc1, nc1.length + nc2.length);
System.arraycopy(nc2, 0, ncr, nc1.length, nc2.length);
return ncr;
}
})
.orElseThrow(() -> new IllegalArgumentException("Empty string"));
return IntStream
.range(0, countCharArray.length / 2)
.mapToObj(i -> countCharArray[i + i] + String.valueOf((char) countCharArray[i + i + 1]))
.collect(Collectors.joining());
}
// simple iterative
public static String compress2(String input) {
var res = new StringBuilder();
int n = 0;
int c = -1;
for (int i = 0; i < input.length(); i++) {
int nc = input.charAt(i);
if (c == nc) {
n++;
} else {
if (c >= 0) {
res.append(n).append((char) c);
}
c = nc;
n = 1;
}
}
if (n > 0) {
res.append(n).append((char) c);
}
return res.toString();
}
// another IntStream.reduce with pure functions (immutable state)
public static String compress3(String input) {
return compress3(input.chars());
}
public static String compress3parallel(String input) {
return compress3(input.chars().parallel());
}
private static String compress3(IntStream chars) {
return chars
.mapToObj(CountChar::single)
.reduce(CountChar::join)
.orElseThrow(() -> new IllegalArgumentException("Empty input"))
.toString();
}
sealed interface CountChar permits CountChar.Single, CountChar.Double {
int firstCount();
char firstCh();
int lastCount();
char lastCh();
CountChar addLastCount(int count);
CountChar removeFirst();
CountChar append(CountChar other);
default CountChar join(CountChar other) {
if (this.lastCh() == other.firstCh()) {
return this.addLastCount(other.firstCount()).append(other.removeFirst());
} else {
return this.append(other);
}
}
static CountChar single(int c) {
return new CountChar.Single(1, (char) c);
}
record Single(int firstCount, char firstCh) implements CountChar {
@Override
public int lastCount() {
return firstCount;
}
@Override
public char lastCh() {
return firstCh;
}
@Override
public CountChar addLastCount(int count) {
return new CountChar.Single(lastCount() + count, firstCh);
}
@Override
public CountChar removeFirst() {
return null;
}
@Override
public CountChar append(CountChar other) {
return other == null ? this : new Double(this, other);
}
@Override
public String toString() {
return firstCount + String.valueOf(firstCh);
}
}
record Double(CountChar first, CountChar last) implements CountChar {
@Override
public int firstCount() {
return first.firstCount();
}
@Override
public char firstCh() {
return first.firstCh();
}
@Override
public int lastCount() {
return last.lastCount();
}
@Override
public char lastCh() {
return last.lastCh();
}
@Override
public CountChar addLastCount(int count) {
return new CountChar.Double(first, last.addLastCount(count));
}
@Override
public CountChar removeFirst() {
var shortenedFirst = first.removeFirst();
return shortenedFirst == null ? last : new Double(shortenedFirst, last);
}
@Override
public CountChar append(CountChar other) {
return other == null ? this : new Double(this, other);
}
@Override
public String toString() {
return first + String.valueOf(last);
}
}
}
// using IntStream.collect with arrays
public static String compress4(String input) {
return compress(input.chars(), ArrayCompressedChars::new);
}
public static String compress4parallel(String input) {
return compress(input.chars().parallel(), ArrayCompressedChars::new);
}
// using IntStream.collect with linked list
public static String compress5(String input) {
return compress(input.chars(), LinkedCompressedChars::new);
}
public static String compress5parallel(String input) {
return compress(input.chars().parallel(), LinkedCompressedChars::new);
}
private static String compress(IntStream chars, Supplier<? extends CompressedChars> ccSupplier) {
return chars
.collect(
ccSupplier,
CompressedChars::append,
CompressedChars::append
)
.toString();
}
interface CharAppendable {
default void append(int ch) {
append((char) ch, 1);
}
void append(char ch, int count);
}
interface CompressedChars extends CharAppendable {
default void append(CompressedChars other) {
other.forEach(this);
}
void forEach(CharAppendable sink);
static String toString(CompressedChars cc) {
var sb = new StringBuilder();
cc.forEach((ch, count) -> sb.append(count).append(ch));
return sb.toString();
}
}
static class ArrayCompressedChars implements CompressedChars {
char[] chars = new char[8];
int[] counts = new int[8];
int len = 0;
@Override
public void append(char ch, int count) {
if (len > 0 && chars[len - 1] == ch) {
counts[len - 1] += count;
} else {
if (len >= chars.length) {
chars = Arrays.copyOf(chars, chars.length * 2);
counts = Arrays.copyOf(counts, counts.length * 2);
}
chars[len] = ch;
counts[len] = count;
len++;
}
}
@Override
public void forEach(CharAppendable sink) {
for (int i = 0; i < len; i++) {
sink.append(chars[i], counts[i]);
}
}
@Override
public String toString() {
return CompressedChars.toString(this);
}
}
static class LinkedCompressedChars implements CompressedChars {
private char ch;
private int count;
private LinkedCompressedChars next, last;
@Override
public void append(char ch, int count) {
if (last == null) {
this.ch = ch;
this.count = count;
this.last = this;
} else if (last.ch == ch) {
last.count += count;
} else {
(last = last.next = new LinkedCompressedChars()).append(ch, count);
}
}
@Override
public void forEach(CharAppendable sink) {
for (var lcs = this; lcs != null; lcs = lcs.next) {
sink.append(lcs.ch, lcs.count);
}
}
@Override
public void append(CompressedChars other) {
if (other instanceof LinkedCompressedChars linkedCC) {
if (last == null) {
this.ch = linkedCC.ch;
this.count = linkedCC.count;
this.next = linkedCC.next;
this.last = linkedCC.last;
} else if (last.ch == linkedCC.ch) {
last.count += linkedCC.count;
if (linkedCC.next != null) {
last.next = linkedCC.next;
last = linkedCC.last;
}
} else {
last.next = linkedCC;
last = linkedCC.last;
}
} else {
CompressedChars.super.append(other);
}
}
@Override
public String toString() {
return CompressedChars.toString(this);
}
}
// simple straight fwd solution
public static String compress6(String input) {
String result = "";
int n = 0;
char[] chars = input.toCharArray();
char prev = chars[0];
for (char c : chars) {
if (c != prev) {
result += n;
result += prev;
n = 0;
prev = c;
}
n++;
}
result += n;
result += prev;
return result;
}
// tests
private static void test(Function<String, String> compressFn) {
test("ABCDE", "1A1B1C1D1E", compressFn);
test("ABBCCCDDDDEEEEE", "1A2B3C4D5E", compressFn);
test("AAABCCCDEEE", "3A1B3C1D3E", compressFn);
}
private static void test(String plain, String expectedCompressed, Function<String, String> compressFn) {
var compressed = compressFn.apply(plain);
System.out.println(plain + " -> " + compressed);
if (!Objects.equals(expectedCompressed, compressed)) {
throw new AssertionError("Expected `" + expectedCompressed + "` but got `" + compressed + "`");
}
}
public static void main(String[] args) {
test(Compression::compress1);
test(Compression::compress1parallel);
test(Compression::compress2);
test(Compression::compress3);
test(Compression::compress3parallel);
test(Compression::compress4);
test(Compression::compress4parallel);
test(Compression::compress5);
test(Compression::compress5parallel);
test(Compression::compress6);
}
}