Skip to content

Instantly share code, notes, and snippets.

@wperron
Created February 27, 2023 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/6833841f1257e79abe1a6a810585f5df to your computer and use it in GitHub Desktop.
Save wperron/6833841f1257e79abe1a6a810585f5df to your computer and use it in GitHub Desktop.
Given a list of numbers, return all groups of repeating consecutive numbers.
/// 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