Multiplying a number in a vector by every other number in the vector

People,

Still trying to find a slightly more useful than "Hello World" program that I can get started with.

If I have a vector with say 10 numbers in it and I want to uniquely multiply each number by each of the other numbers in the vector - that would give me 45 results - presumably in another vector. What is the simplest way to do this?

Thanks,
Phil.

This would be an easy solution:

fn product_combinations<T>(numbers: &[T]) -> Vec<T>
where
    T: Copy + Mul<Output = T>
{
    numbers
        .iter()
        .copied()
        .enumerate()
        .flat_map(|(i, x)| {
            numbers[i + 1..].iter().copied().map(move |y| x * y)
        })
        .collect()
}
1 Like

@H2CO3 ,

Thanks! - I will start playing with that . .

P.

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.