gpt4 book ai didi

rust - 如何计算N次向量的笛卡尔积?

转载 作者:行者123 更新时间:2023-12-03 11:36:19 24 4
gpt4 key购买 nike

我正在寻找带有签名fn product(vector: &Vec<i32>, n: &i32) -> Vec<Vec<i32>>或类似功能的函数。一个例子:

assert_eq!(
product(vec![1, 2, 3, 4], 2),
[
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[3, 1],
[3, 2],
[3, 3],
[3, 4],
[4, 1],
[4, 2],
[4, 3],
[4, 4]
],
)
我已经尝试过使用 iproduct crate 中的 itertools :
use itertools::iproduct; // 0.10.0

fn product(vector: &Vec<i32>, n: &i32) -> Vec<Vec<i32>> {
let mut result = Vec::new();

for _ in 0..*n {
result = iproduct!(result.iter(), vector.iter()).collect();
}

result
}
产生此错误:
error[E0277]: a value of type `Vec<_>` cannot be built from an iterator over elements of type `(&_, &i32)`
--> src/lib.rs:7:58
|
7 | result = iproduct!(result.iter(), vector.iter()).collect();
| ^^^^^^^ value of type `Vec<_>` cannot be built from `std::iter::Iterator<Item=(&_, &i32)>`
|
= help: the trait `FromIterator<(&_, &i32)>` is not implemented for `Vec<_>`
我该如何解决这个问题?

最佳答案

  • 您究竟希望result是哪种类型?要使其成为返回值,必须为Vec<Vec<i32>>,对吗?但是,然后iproduct!(result.iter(), vector.iter())返回一个Iterator<Item = (&Vec<i32>, &i32)>(您可以通过明确指定result的类型来看到它),并将Vec<(&Vec<i32>, &i32)>分配给result,这是行不通的。因此,您需要先将map编码为(&Vec<i32>, &i32)
  • 在一开始,Vec<i32>为空,因此其乘积为空。它需要包含一个元素。该元素应该是什么?
  • 通过引用获取result毫无意义。同样,它是preferred接受切片n而不是&[i32]

  • 如果解决了所有这些问题,您将获得
    S  
    o
    m
    e

    s
    p
    o
    i
    l
    e
    r

    s
    p
    a
    c
    e

    f
    o
    r

    y
    o
    u

    t
    o

    t
    r
    y

    y
    o
    u
    r
    s
    e
    l
    f
    Playground
    use itertools::iproduct;

    fn product(vector: &[i32], n: i32) -> Vec<Vec<i32>> {
    let mut result: Vec<Vec<i32>> = vec![vec![]];

    for _ in 0..n {
    result = iproduct!(result.iter(), vector.iter())
    .map(|(v, x)| {
    let mut v1 = v.clone();
    v1.push(*x);
    v1
    })
    .collect();
    }

    result
    }
    我会选择 &Vec<i32> 而不是自己使用 flat_map

    关于rust - 如何计算N次向量的笛卡尔积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65780507/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com