↑Programmieren in Rust
fn reverse(a: &mut [i32]) { let n = a.len(); for i in 0..n/2 { a.swap(i, n-1-i); } } // Typ-generisch: fn reverse<T>(a: &mut [T]) { let n = a.len(); for i in 0..n/2 { a.swap(i, n-1-i); } } fn main(){ let mut a: Vec<i32> = vec![1, 2, 3, 4]; reverse(&mut a); println!("{:?}", a); }
fn take_even(a: &[i32]) -> Vec<i32> { let n = a.len(); let m = if n%2 == 0 {n/2} else {n/2 + 1}; let mut acc: Vec<i32> = Vec::with_capacity(m); for i in 0..m { acc.push(a[2*i]); } acc } fn take_odd(a: &[i32]) -> Vec<i32> { let m = a.len()/2; let mut acc: Vec<i32> = Vec::with_capacity(m); for i in 0..m { acc.push(a[2*i + 1]); } acc } fn main(){ let a: Vec<i32> = vec![1, 2, 3, 4]; let v = take_even(&a); let w = take_odd(&a); println!("{:?}, {:?}", v, w); }
use std::iter::FromIterator; use std::collections::HashSet; use std::hash::Hash; fn unique<T: Eq + Hash>(v: Vec<T>) -> Vec<T> { HashSet::<T>::from_iter(v.into_iter()).into_iter().collect() } fn main() { let v: Vec<i32> = vec![1, 4, 5, 2, 3, 1, 4]; println!("{:?}", unique(v)); }
use std::iter::FromIterator; use std::collections::BTreeSet; fn unique<T: Eq + Ord>(v: Vec<T>) -> Vec<T> { BTreeSet::<T>::from_iter(v.into_iter()).into_iter().collect() } fn main() { let v: Vec<i32> = vec![1, 4, 5, 2, 3, 1, 4]; println!("{:?}", unique(v)); }