-
Notifications
You must be signed in to change notification settings - Fork 13
/
ArrayRanges.java
58 lines (48 loc) · 1.44 KB
/
ArrayRanges.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
package by.andd3dfx.common;
import lombok.AllArgsConstructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* <pre>
* Build string with ranges for defined list:
* [1,4,5,2,3,9,8,11,0] => "0-5,8-9,11"
* [1,4,3,2] => "1-4"
* [1,4] => "1,4"
* </pre>
*
* @see <a href="https://youtu.be/ql6TROfbnYk">Video solution</a>
*/
public class ArrayRanges {
@AllArgsConstructor
public class Range {
private int left;
private int right;
}
public String compact(int[] values) {
if (values.length == 0) {
return "";
}
Arrays.sort(values);
List<Range> ranges = new ArrayList<>();
Range draftRange = new Range(values[0], values[0]);
ranges.add(draftRange);
for (var value : values) {
if ((value - draftRange.right) <= 1) {
draftRange.right = value;
continue;
}
draftRange = new Range(value, value);
ranges.add(draftRange);
}
return ranges.stream()
.map(range -> {
if (range.left == range.right) {
return String.valueOf(range.left);
}
return range.left + "-" + range.right;
})
.collect(Collectors.joining(","));
}
}