-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrange_extraction.rs
33 lines (30 loc) · 952 Bytes
/
range_extraction.rs
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
pub fn range_extraction(a: &[i32]) -> String {
let mut groups: Vec<Vec<i32>> = Vec::new();
for &num in a {
let current_group = groups.last_mut();
match current_group {
Some(group) => {
let last = group.last().unwrap();
if num - last == 1 {
group.push(num);
} else {
let group = vec![num];
groups.push(group);
}
}
None => {
let group = vec![num];
groups.push(group);
}
}
}
let strings = groups
.iter()
.map(|group| match group.len() {
1 => group.first().unwrap().to_string(),
2 => format!("{},{}", group[0], group[1]),
_ => format!("{}-{}", group.first().unwrap(), group.last().unwrap()),
})
.collect::<Vec<_>>();
strings.join(",")
}