2

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]

radionnazmiev
  • 153
  • 3
  • 8
  • Given that this is a codewars problem, what specifically are you having trouble with? – kmdreko Apr 18 '21 at 20:21
  • 1
    Here is a question solving a similar problem requiring grouping sequences of a vec: https://stackoverflow.com/questions/50380352/how-can-i-group-consecutive-integers-in-a-vector-in-rust – kmdreko Apr 18 '21 at 20:27
  • I'm trying to solve the kata without converting the original 2d matrix from row-major-order to column-major-order. I was thinking about either windows()+cmp_by() or group_by() but cant get my head aroud to come up with a solution for it https://github.com/radionnazmiev/blobservation_2_merge_inert_blobs/blob/master/src/lib.rs – radionnazmiev Apr 18 '21 at 22:33

1 Answers1

1

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.

smitop
  • 4,770
  • 2
  • 20
  • 53