algorithmz/array/remove_duplicates.rs
1/// Remove duplicate elements from an array, preserving order.
2///
3/// Takes a list reference and returns a `Vec<i32>` or an error explaining the situation.
4///
5/// # Examples
6///
7/// Basic usage:
8/// ```
9/// let result = algorithmz::array::remove_duplicates(&[1,1,2,3,3,4,4,5]).unwrap();
10/// assert_eq!(result, [1,2,3,4,5]);
11/// ```
12///
13/// Match example:
14/// ```
15/// use algorithmz::array::remove_duplicates;
16/// match remove_duplicates(&[1,1,2,3,3,4,5,5,9]) {
17/// Ok(n) => println!("The result was: {:?}",n),
18/// Err(e) => eprintln!("The error was: {}",e),
19/// }
20/// ```
21pub fn remove_duplicates(list: &[i32]) -> Result<Vec<i32>, String> {
22 if list.is_empty() {
23 return Err("Cannot remove duplicates from an empty list.".to_string());
24 }
25 let mut result: Vec<i32> = Vec::new();
26 let mut seen: Vec<i32> = Vec::new();
27 for item in list {
28 if !seen.contains(item) {
29 seen.push(*item);
30 result.push(*item);
31 }
32 }
33 Ok(result)
34}
35