diff --git a/Cargo.lock b/Cargo.lock index 023d81a..1acaa6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5,3 +5,7 @@ version = 3 [[package]] name = "balance" version = "0.1.0" + +[[package]] +name = "repeated-groups" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index bd112fd..d919de0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,5 @@ [workspace] members = [ - "balance" + "balance", + "repeated-groups", ] diff --git a/repeated-groups/Cargo.toml b/repeated-groups/Cargo.toml new file mode 100644 index 0000000..fa59372 --- /dev/null +++ b/repeated-groups/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "repeated-groups" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/repeated-groups/src/main.rs b/repeated-groups/src/main.rs new file mode 100644 index 0000000..eb662e3 --- /dev/null +++ b/repeated-groups/src/main.rs @@ -0,0 +1,65 @@ +/// Given a list of numbers, return all groups of repeating consecutive numbers. +/// +/// Examples: +/// +/// ``` +/// > repeatedGroups([1, 2, 2, 4, 5]) +/// [[2, 2]] +/// +/// > repeatedGroups([1, 1, 0, 0, 8, 4, 4, 4, 3, 2, 1, 9, 9]) +/// [[1, 1], [0, 0], [4, 4, 4], [9, 9]] +/// ``` + +fn main() { + println!("Hello, world!"); +} + +fn repeated_groups(nums: Vec) -> Vec> { + let mut i = 0; + let mut j = 0; + + let mut res: Vec> = vec![]; + let mut curr: Vec = vec![]; + + while j < nums.len() { + if nums[i] != nums[j] { + if curr.len() > 1 { + res.push(curr); + } + + i = j; + j += 1; + curr = vec![nums[i]]; + continue; + } + + curr.push(nums[i]); + j += 1; + } + + // If the last iteration is a repeated group, the loop exits before appending + // the last group to the results, so we check here for what the last group was + // and add it to the result if need be. + if curr.len() > 1 { + res.push(curr); + } + + res +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_repeated_groups() { + let nums = vec![1, 2, 2, 4, 5]; + assert_eq!(vec![vec![2, 2]], repeated_groups(nums)); + + let nums = vec![1, 1, 0, 0, 8, 4, 4, 4, 3, 2, 1, 9, 9]; + assert_eq!( + vec![vec![1, 1], vec![0, 0], vec![4, 4, 4], vec![9, 9]], + repeated_groups(nums) + ); + } +}