haphaeu
December 11, 2024, 1:51pm
1
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))>
alice
December 11, 2024, 2:50pm
2
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
haphaeu
December 13, 2024, 1:33pm
3
Magic! tuple_combinations
another tool in the toolbox Thanks
Here's the full implementation code of my AoC solutions .
system
Closed
March 13, 2025, 1:34pm
4
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.