Browse Source

initial commit

master
Jim Infield 3 years ago
commit
3c354f1215
  1. 1
      .gitignore
  2. 7
      Cargo.lock
  3. 8
      Cargo.toml
  4. 11
      README.md
  5. 54
      src/main.rs

1
.gitignore

@ -0,0 +1 @@
/target

7
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"

8
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]

11
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]

54
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<T: PartialEq + std::fmt::Display + std::fmt::Debug>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
a.into_iter()
.filter(
|i| b.iter().all(|e| *e != *i))
.collect::<Vec<T>>()
}
fn not_contains<T: PartialEq>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
a.into_iter().filter(|x| !b.contains(x)).collect()
}
fn retains<T: PartialEq>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
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]);
}
}
Loading…
Cancel
Save