R
R
RADION NAZMIEV2021-04-18 19:36:37
Rust
RADION NAZMIEV, 2021-04-18 19:36:37

How to split a vector into subvectors of different lengths?

Let's say there is a vector that I want to turn into then sum all the elements of the subvectors and get where the zeros are omitted. Elements are grouped according to the principle 9>7>6>3.. 3 is not greater than 4, so 3 will be the last element of this subvector. Source: codewars quest - Blobservation 2: Merge Inert Blobs [9,7,6,3,4,0,1,7,3,9][25,5,10,9]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-04-18
@radionnazmiev

If you are not going to change the data, you can create a new vector from readonly slices.
A separate task is to find indices where sorting breaks down (I don’t remember what it’s called, but it has a term)
These points can be found with a simple loop, within which just you can create slices and push to a new vector.
Then on this vector with slices you do map and sum

L
lo-fi, 2021-05-07
@hrls

fn main() {
    let values: Vec<u64> = vec![9, 7, 6, 3, 4, 0, 1, 7, 3, 9];

    let (_, groups): (Option<u64>, Vec<Vec<u64>>) = values
        .into_iter()
        .filter(|value| *value > 0)
        .fold((None, vec![]), |(previous, mut groups), current| {
            match previous {
                Some(previous) if previous >= current => {
                    if let Some(last_group) = groups.last_mut() {
                        last_group.push(current);
                    } else {
                        groups.push(vec![current]);
                    }
                }
                _ => groups.push(vec![current]),
            };
            (Some(current), groups)
        });

    dbg!(&groups);

    let sums: Vec<u64> = groups
        .into_iter()
        .map(|group| group.into_iter().sum())
        .collect();

    dbg!(&sums);
}

https://play.rust-lang.org/?version=stable&mode=de...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question