How to resolve the algorithm Cartesian product of two or more lists step by step in the Rust programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Cartesian product of two or more lists step by step in the Rust programming language
Table of Contents
Problem Statement
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: and, in contrast: Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Cartesian product of two or more lists step by step in the Rust programming language
Source code in the rust programming language
fn cartesian_product(lists: &Vec<Vec<u32>>) -> Vec<Vec<u32>> {
let mut res = vec![];
let mut list_iter = lists.iter();
if let Some(first_list) = list_iter.next() {
for &i in first_list {
res.push(vec![i]);
}
}
for l in list_iter {
let mut tmp = vec![];
for r in res {
for &el in l {
let mut tmp_el = r.clone();
tmp_el.push(el);
tmp.push(tmp_el);
}
}
res = tmp;
}
res
}
fn main() {
let cases = vec![
vec![vec![1, 2], vec![3, 4]],
vec![vec![3, 4], vec![1, 2]],
vec![vec![1, 2], vec![]],
vec![vec![], vec![1, 2]],
vec![vec![1776, 1789], vec![7, 12], vec![4, 14, 23], vec![0, 1]],
vec![vec![1, 2, 3], vec![30], vec![500, 100]],
vec![vec![1, 2, 3], vec![], vec![500, 100]],
];
for case in cases {
println!(
"{}\n{:?}\n",
case.iter().map(|c| format!("{:?}", c)).collect::<Vec<_>>().join(" × "),
cartesian_product(&case)
)
}
}
You may also check:How to resolve the algorithm Input loop step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Greatest common divisor step by step in the REXX programming language
You may also check:How to resolve the algorithm LZW compression step by step in the Java programming language
You may also check:How to resolve the algorithm Empty program step by step in the XSLT programming language
You may also check:How to resolve the algorithm Dot product step by step in the Run BASIC programming language