Created
June 20, 2021 18:43
-
-
Save NickyMeuleman/dfec951450ed1729a8b20c7bcbcdca99 to your computer and use it in GitHub Desktop.
Exercism.io Sublist in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cmp::Ordering; | |
#[derive(Debug, PartialEq)] | |
pub enum Comparison { | |
Equal, | |
Sublist, | |
Superlist, | |
Unequal, | |
} | |
pub fn sublist<T: PartialEq>(first_list: &[T], second_list: &[T]) -> Comparison { | |
fn is_superlist<T: PartialEq>(longer: &[T], shorter: &[T]) -> bool { | |
shorter.is_empty() || longer.windows(shorter.len()).any(|window| window == shorter) | |
} | |
match first_list.len().cmp(&second_list.len()) { | |
Ordering::Equal if first_list == second_list => Comparison::Equal, | |
Ordering::Greater if is_superlist(first_list, second_list) => Comparison::Superlist, | |
Ordering::Less if is_superlist(second_list, first_list) => Comparison::Sublist, | |
_ => Comparison::Unequal, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment