Replacing consecutive numbers with dash between first and last in a range
// Replacing consecutive numbers with dash between first and last in a range
fn convert_to_range(first: i32, last: i32) -> String {
if last - first >= 2 {
first.to_string() + "-" + &last.to_string()
} else if first != last {
first.to_string() + "," + &last.to_string()
} else {
first.to_string()
}
}
fn range_extraction(a: &[i32]) -> String {
let mut r: Vec<i32> = Vec::new();
let mut finals: Vec<String> = Vec::new();
for &x in a.iter() {
match r.last() {
Some(y) => {
if x - y == 1 {
r.push(x);
} else {
finals.push(convert_to_range(*r.first().unwrap(), *r.last().unwrap()));
r = vec![x];
}
},
None => {
r.push(x);
},
}
}
finals.push(convert_to_range(*r.first().unwrap(), *r.last().unwrap()));
finals.join(",")
}
fn main() {
// answer: "-3--1,2,10,15,16,18-20"
println!("{} ", range_extraction(&[-3,-2,-1,2,10,15,16,18,19,20]));
}