radionnazmiev
radionnazmiev

Reputation: 162

How to group elements of a vector by a pattern?

How to break a vector such as [9,7,6,3,4,0,1,7,3,9] -> [[9,7,6,3],[4,1],[7,3],[9]] -> [25,5,10,9]?

The logic behind it is that a vector is broken into subvectors where each subsequent element is smaller than previous one(0'z are ignored), a descending sequence . When the subvectors are formed, each one is replaced with a sum of all of its elements.

[https://www.codewars.com/kata/5f8fb3c06c8f520032c1e091][1]

Upvotes: 2

Views: 2004

Answers (1)

loops
loops

Reputation: 5635

Iterate over the elements of the nums to build up the split. For every number, compare it to the last number to decide whether to create a sublist, or append to the existing one:

let nums = vec![9,7,6,3,4,0,1,7,3,9];
let mut split: Vec<Vec<i32>> = vec![vec![]];
for num in nums.iter().filter(|n| **n != 0) {
    let sublist = split.last_mut().unwrap();
    match sublist.last_mut() {
        Some(x) if num > x => {
            split.push(vec![*num]);
        }
        _ => sublist.push(*num),
    }
}
let split = split; // make split immmutable
let summed: Vec<i32> = split.iter().map(|v| v.iter().sum()).collect();

(try in playground)

It's probably possible to make a more elegant solution using Iterator::partition_in_place, but that fn is sadly unstable for now.

Upvotes: 1

Related Questions