add repeated groups implementation (issue #289)
parent
d9064f77df
commit
087137a74a
@ -1,4 +1,5 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"balance"
|
"balance",
|
||||||
|
"repeated-groups",
|
||||||
]
|
]
|
||||||
|
@ -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]
|
@ -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<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)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue