How to merge two Vec<u8> into a Vec<(u8, u8)>

i'm trying to produce out of two Vec<u8>s any combinations of the items of the vector into a Vec<(u8, u8)>

let fst: Vec<u8> = vec![0, 1]
let snd: Vec<u8> = vec![2, 3]

// the aim is to produce this vec![(0, 2), (0, 3), (1, 2), (1, 3)]

I'm trying to do it through folds but can only produce a &Vec<(u8, u8)> and wondering ig they're is a prefered way ?

What I've come up so far

let fst: Vec<u8> = vec![0, 1]
let snd: Vec<u8> = vec![2, 3]

let res = fst.into_iter().fold(&vec![], |all: &Vec<(u8, u8)>, a| {
    let temp = &suits_b.into_iter().fold(all, |cur: &Vec<(u8, u8)>, b| {
        cur.push((a, b));
        cur
    });
    temp
});

An existing cartesian product operation is probably best; but if you’re interested in doing this with only things like map and flat_map, that works, too:

fn main() {
    let fst: Vec<u8> = vec![0, 1];
    let snd: Vec<u8> = vec![2, 3];
    let res = fst.iter().flat_map(|x| snd.iter().map(|y| (*x, *y))).collect::<Vec<_>>();
    assert_eq!(res, vec![(0, 2), (0, 3), (1, 2), (1, 3)]);
}
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.