commit 3c354f12158e1e8e12a43c75d20ae4d09ee16392 Author: Jim Infield Date: Fri Jul 23 09:51:20 2021 -0500 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..6c461b9 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "arraydiff" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..cdbb41e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "arraydiff" +version = "0.1.0" +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/README.md b/README.md new file mode 100644 index 0000000..769074c --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +Your goal in this kata is to implement a difference function, which subtracts +one list from another and returns the result. + +It should remove all values from list a, which are present in list b keeping +their order. + +array_diff(vec![1,2], vec![1]) == vec![2] If a value is present in b, all of its +occurrences must be removed from the other: + +array_diff(vec![1,2,2,2,3], vec![2]) == vec![1,3] + diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..4fd0577 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,54 @@ +#![allow(unused)] +fn main() { + println!(); + let args = vec![ + (vec![1,2], vec![1]), + (vec![1,2,2], vec![2]), + (vec![1,2,2], vec![]), + (vec![], vec![1,2]), + (vec![1,2,3], vec![1,2]), + ]; + + for (arg1, arg2) in args { + println!("{:?} \tless {:?} \t leaves {:?}, {:?}, {:?}\n", + arg1.clone(), + arg2.clone(), + array_diff(arg1.clone(), arg2.clone()), + not_contains(arg1.clone(), arg2.clone()), + retains(arg1, arg2) + ); + }; + + println!(); +} + +fn array_diff(a: Vec, b: Vec) -> Vec { + a.into_iter() + .filter( + |i| b.iter().all(|e| *e != *i)) + .collect::>() +} + +fn not_contains(a: Vec, b: Vec) -> Vec { + a.into_iter().filter(|x| !b.contains(x)).collect() +} + +fn retains(a: Vec, b: Vec) -> Vec { + let mut a = a; + a.retain(|x| !b.contains(x)); + a +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn returns_expected() { + assert_eq!(array_diff(vec![1,2], vec![1]), vec![2]); + assert_eq!(array_diff(vec![1,2,2], vec![1]), vec![2,2]); + assert_eq!(array_diff(vec![1,2,2], vec![2]), vec![1]); + assert_eq!(array_diff(vec![1,2,2], vec![]), vec![1,2,2]); + assert_eq!(array_diff(vec![], vec![1,2]), vec![]); + assert_eq!(array_diff(vec![1,2,3], vec![1,2]), vec![3]); + } +}