How to pattern match a combination

I guess the code says more than my words....

How could i pattern match those 4 coordinates in the for loop?

use itertools::Itertools;

fn main() {
    let nodes: Vec<(u8, u8)> = vec![(1, 2), (3, 4), (5, 6)];
    let nodes_pairs = nodes
        .into_iter()
        .combinations(2);
        
    for pair in nodes_pairs {
        // TODO: there *must* be a better way to achieve this:
        let (v1, v2) = (pair[0], pair[1]);
        let (i1, j1) = (v1.0, v1.1);
        let (i2, j2) = (v2.0, v2.1);

        println!("({i1}, {j1}), ({i2}, {j2})");
    }
}

Playground

In Python one could directly get the indices, something like:

for (i, j), (k, l) in nodes_pairs:

Since nodes_pairs is a Vec<((u32, u32), (u32, u32))>

Use tuple_combinations instead:

use itertools::Itertools;

fn main() {
    let nodes: Vec<(u8, u8)> = vec![(1, 2), (3, 4), (5, 6)];
    let nodes_pairs = nodes
        .into_iter()
        .tuple_combinations();
    
    for ((i1, j1), (i2, j2)) in nodes_pairs {
        println!("({i1}, {j1}), ({i2}, {j2})");
    }
}

or if you must use the Vec based combinations:

use itertools::Itertools;

fn main() {
    let nodes: Vec<(u8, u8)> = vec![(1, 2), (3, 4), (5, 6)];
    let nodes_pairs = nodes
        .into_iter()
        .combinations(2)
        .map(|vec| (vec[0], vec[1]));
    
    for ((i1, j1), (i2, j2)) in nodes_pairs {
        println!("({i1}, {j1}), ({i2}, {j2})");
    }
}

The problem is that a vector might not have a length of two, so you can't match directly on the vector.

6 Likes

Magic! tuple_combinations another tool in the toolbox :slight_smile: Thanks

Here's the full implementation code of my AoC solutions .