From 3e7544fd6b33a7753a7e9a944305d5494320dd4b Mon Sep 17 00:00:00 2001 From: ridethepig Date: Sun, 19 Feb 2023 10:34:14 +0000 Subject: [PATCH] warm up --- week1/part-2-warmup/src/main.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/week1/part-2-warmup/src/main.rs b/week1/part-2-warmup/src/main.rs index d5e231d..6c15a08 100644 --- a/week1/part-2-warmup/src/main.rs +++ b/week1/part-2-warmup/src/main.rs @@ -7,15 +7,38 @@ fn main() { } fn add_n(v: Vec, n: i32) -> Vec { - unimplemented!() + // The function should return a new vector whose elements are the numbers in the original vector v with n added to each number. + let mut newvec = Vec::new(); + for i in v { + newvec.push(i + n); + } + newvec } fn add_n_inplace(v: &mut Vec, n: i32) { - unimplemented!() + // does the same thing as add_n, but modifies v directly (in place) and does not return anything. + for i in v { + *i += n; + } } fn dedup(v: &mut Vec) { - unimplemented!() + // that removes duplicate elements from a vector in-place (i.e. modifies v directly). + // If an element is repeated anywhere in the vector, you should keep the element that appears first. + // You may want to use a HashSet for this. + let mut _hash = HashSet::new(); + let mut _repeated = Vec::new(); + for i in 0..v.len() { + if _hash.contains(&v[i]) { + _repeated.push(i); + } else { + _hash.insert(v[i]); + } + } + _repeated.reverse(); + for i in _repeated { + v.remove(i); + } } #[cfg(test)]