Created
February 27, 2023 14:07
-
-
Save wperron/6833841f1257e79abe1a6a810585f5df to your computer and use it in GitHub Desktop.
Given a list of numbers, return all groups of repeating consecutive numbers.
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
/// 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<isize>) -> Vec<Vec<isize>> { | |
let mut i = 0; | |
let mut j = 0; | |
let mut res: Vec<Vec<isize>> = vec![]; | |
let mut curr: Vec<isize> = 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) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment