Listenin küçükten büyüğe sıralanmış sayılardan oluştuğunu varsayıyorum:
// Rust
fn print_items(seen: &Vec<i32>) {
if seen.len() >= 3 {
println!("({}: {}) ", seen[0], seen.last().unwrap());
} else {
for i in seen {
println!("{} ", i);
}
}
}
fn solution(list: &[i32]) {
let mut seen = Vec::new();
for &i in list {
match seen.last() {
Some(&last) => {
if i != last + 1 {
print_items(&seen);
seen.clear();
}
seen.push(i);
}
None => seen.push(i),
}
}
print_items(&seen);
}
fn main() {
solution(&[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
}
Bu daha iyi:
fn print_items(slice: &[i32], from: usize, to: usize) {
if to-from >= 2 {
println!("({}: {}) ", slice[from], slice[to]);
} else {
for i in &slice[from..=to] {
println!("{} ", i);
}
}
}
fn solution(list: &[i32]) {
let (mut from, mut to) = (0, 0);
for &i in &list[1..] {
if list[to]+1 != i {
print_items(list, from, to);
from = to+1;
}
to += 1;
}
print_items(list, from, to);
}
fn main() {
solution(&[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
}
Sanırım forum Rust kodu için renklendirmeye sahip değil @ismailarilik.